Benjamin Rodriguez Benjamin Rodriguez - 2 months ago 7
C++ Question

Iterate through a pointer set that contains string vectors in C++

This is my declaration of the set:

set< vector<string> >* tuples = new set< vector<string> >();


And this is how I am trying to iterate through it:

for(set< vector<string> >::iterator it = tuples->begin(); it != tuples->end(); it++){
if(it[column] == value){
rowResults->insert(*it);
}
}


but I get an error

no match for ‘operator[]’ (operand types are ‘std::set<std::vector<std::__cxx11::basic_string<char> > >::iterator {aka std::_Rb_tree_const_iterator<std::vector<std::__cxx11::basic_string<char> > >}’ and ‘int’)
if(it[column] == value){
^

Answer

You're applying [] to the iterator instead of to the object to which it points. You need to dereference the iterator (and mind operator precedence!):

for(set< vector<string> >::iterator it = tuples->begin(); it != tuples->end(); ++it){
    if((*it)[column] == value){
        rowResults->insert(*it);
    }
}

Note that with iterators, it's better to use ++it instead of it++ in loops, since the latter can be less efficient under insufficient optimisation.