从矢量对中获取值时出错

Bry*_*ong 5 c++ iterator vector

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

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!
}
Run Code Online (Sandbox Code Playgroud)

错误信息:

main_v10.cpp:165:25:错误:'std :: vector >>> :: iterator'没有名为'first'main_v10.cpp的成员:165:56:错误:'std :: vector >>> :: iterator'有没有名为'second'的会员

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

lee*_*mes 7

这个问题也适用于指针(迭代器的行为非常类似于指针).有两种方法可以访问指针(或迭代器)指向的值的成员:

it->first     // preferred syntax: access member of the pointed-to object
Run Code Online (Sandbox Code Playgroud)

要么

(*it).first   // verbose syntax: dereference the pointer, access member on it
Run Code Online (Sandbox Code Playgroud)

运算符优先级将表达式转换为

*(it.first)   // wrong! tries to access a member of the pointer (iterator) itself
Run Code Online (Sandbox Code Playgroud)

尝试访问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;
}
Run Code Online (Sandbox Code Playgroud)

请注意,地图和对矢量之间的本质区别在于地图通过按键对元素进行排序来重新排列元素.之后无法查询插入顺序.在某些情况下,您不希望这样做(当插入顺序很重要时),因此在这种情况下,您的解决方案或包含至少包含键和值的自定义类型的向量是正确的解决方案.