5

为什么在对向量的迭代器中访问对的值时会出现以下错误?

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

错误信息:

main_v10.cpp:165:25:错误:“std::vector > >::iterator”没有名为“first”的成员 main_v10.cpp:165:56:错误:“std::vector > >::iterator”有没有名为“第二”的成员</p>

我怎样才能解决这个问题?

4

1 回答 1

7

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.

于 2013-02-15T07:41:15.393 回答