0

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){
         ^

3 Answers3

0

it is an iterator, not the vector object itself. To access the vector object just use *it

Even better: get rid of the confusing iterator type by defining a reference (here constant ref since we don't seem to need a non-const) to the element itself.

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

as no decent C++ answer cannot not mention the "new" C++11, note that if you use -std=c++11 option, the syntax is much better to iterate on a list

for(auto v : *tuples)
{
    if(v[column] == value){
        rowResults->insert(v);
    }
}
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
0

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.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
0

You may avoid iterator with something like:

std::set<std::vector<std::string>>
computeRowResult(const std::set<std::vector<std::string>>& input,
                 int column,
                 const std::string& value)
{
    std::set<std::vector<std::string>> rowResults;

    for (const auto& v : input) {
        if (v[column] == value) {
            rowResults.insert(v);
        }
    }
    return rowResults;
}

or avoiding the manual loop with

std::set<std::vector<std::string>>
computeRowResult(const std::set<std::vector<std::string>>& input,
                 int column,
                 const std::string& value)
{
    std::set<std::vector<std::string>> rowResults;

    std::copy_if(input.begin(), input.end(),
                 std::inserter(rowResults, rowResults.end()),
                 [&](const auto& v) { return v[column] == value; });

    return rowResults;
}

Demo

Jarod42
  • 203,559
  • 14
  • 181
  • 302