mercredi 6 janvier 2016

Iterator over a vector of strings,got as input from console giving segemntation fault

I have two different programs here,both of which creates a BST of strings and then checks if a given string is there in the BST.

The first program works fine when I pass the dereferencing of an iterator of the vector of strings to the find function.

But the second program fails and gives segmentation error when I take an input from the user and then pass the dereferencing of an iterator over the vector of that input string.

Why does it fail when I get an input from the user?

Working program

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include<typeinfo>
using namespace std;

int main() 
{

    vector<std::string> vn;
    set<std::string> names;
    BST<std::string> b2;

    vn.push_back("AAA");
    vn.push_back("BBB");
    vn.push_back("CCC");

    vector<std::string>::iterator vit = vn.begin();
    for(; vit != vn.end(); vit++)
    {
         b2.insert(*vit);
         names.insert(*vit);
    }

    vit = vn.begin();
    for(; vit != vn.end(); ++vit) 
    {
         if(*(b2.find(*vit)) != *vit) 
         {
              cout << "Incorrect return value when finding " << *vit;
              return -1;
         }
    }
}

Error giving program

#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <set>
#include<typeinfo>
using namespace std;

int main() 
{

    vector<std::string> vn;
    set<std::string> names;
    std::string cur_str;
    BST<std::string> b2;

    vn.push_back("AAA");
    vn.push_back("BBB");
    vn.push_back("CCC");


    vector<std::string>::iterator vit = vn.begin();
    for(; vit != vn.end(); vit++)
    {
         b2.insert(*vit);
         names.insert(*vit);
    }

    std::getline(std::cin, cur_str);
    vector<std::string> vn2;
    vn2.push_back(cur_str);
    vector<std::string>::iterator vit2 = vn2.begin();

    vit = vn.begin();
    for(; vit != vn.end(); ++vit) 
    {
         if(*(b2.find(*vit2)) != *vit) (gives segmentation fault in this line)
         {
              cout << "Incorrect return value when finding " << *vit << endl;
              return -1;
         }
    }
}

find function

template<typename Data> (Declared at the beginning)
iterator find(const Data& item) const
{
    BSTNode<Data> * currentNode = root;
    while(NULL != currentNode) 
    {
        if(item < currentNode->data) 
        {
            currentNode = currentNode->left;
        }
        else if(currentNode->data < item)
        {
            currentNode = currentNode->right;
        }
        else 
        {
             // item == currentNode->data
             return iterator(currentNode);
        }
    }
return end();
 }

Aucun commentaire:

Enregistrer un commentaire