Error in getting value from pairs vector

Why am I getting the error below when accessing pair values ​​in a pair vector iterator?

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 does not have a name with the name' first main_v10.cpp: 165: 56: error: 'std :: vector → :: iterator does not have a name with the name 'second

How can i fix this?

+5
source share
1 answer

This is a problem that applies to pointers (the iterator behaves like a pointer). There are two ways to access a member of a value that a 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

Operator Priority Turns Your Expression Into

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

first , , first. , .


std::map . vector<pair<int,string> > map<int,string>, (, ), :

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;
}

, , , . . , ( ), , , .

+7

All Articles