Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error in Getting Value from Vector of Pairs

Why do I get the error below when accessing the pair's values in a iterator of a vector of pairs?

vector< pair<int,string> > mapper;
if(Hash(input, chordSize) != id){
    mapper.push_back(make_pair(tmp, input));
}

for (vector< pair<int,string> >::iterator it = mapper.begin(); it != mapper.end(); ++it)
{
    cout << "1st: " << *it.first << " "           // <-- error!
         << "2nd: " << *it.second << endl;        // <-- error!
}

Error message:

main_v10.cpp:165:25: error: ‘std::vector > >::iterator’ has no member named ‘first’ main_v10.cpp:165:56: error: ‘std::vector > >::iterator’ has no member named ‘second’

How can I fix this?

like image 561
Bryan Wong Avatar asked Feb 15 '13 07:02

Bryan Wong


1 Answers

This is an issue which applies for pointers, too (an iterator behaves pretty much like a pointer). There are two ways to access a member of the value the pointer (or iterator) points to:

it->first     // preferred syntax: access member of the pointed-to object

or

(*it).first   // verbose syntax: dereference the pointer, access member on it

The operator precedence turns your expression into

*(it.first)   // wrong! tries to access a member of the pointer (iterator) itself

which tries to access the member first on the iterator itself, which fail, because the it doesn't have a member called first. If it did, you'd then dereference the value of that member.


However, in most such cases you should use std::map to map from key to values. Instead of vector<pair<int,string> >, you should use map<int,string> which behaves similar (insertion, iteration and stuff also happens with pairs), but it sorts the keys in the data structure for faster random access:

map<int,string> mapper;
if(Hash(input, chordSize) != id){
    mapper.push_back(make_pair(tmp, input));
}

for (map<int,string>::iterator it = mapper.begin(); it != mapper.end(); ++it)
{
    cout << "1st: " << it->first << " "
         << "2nd: " << it->second << endl;
}

Note that an essential difference between a map and a vector of pairs is that a map rearranges the elements by sorting them by their key. The order of insertion can't be queried afterwards. There are cases in which you don't want to do that (when insertion order matters), so in such cases either your solution or a vector with custom types containing at least the key and value are the correct solution.

like image 127
leemes Avatar answered Nov 02 '22 14:11

leemes