从对的向量中获取值时出错

Error in Getting Value from Vector of Pairs

本文关键字:出错 获取 向量      更新时间:2023-10-16

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

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>>::迭代器"没有名为"first"的成员main_v10.cpp:165:56:错误:"std::vector>>::迭代器"没有名为"second"的成员

我该怎么解决这个问题?

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

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

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

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

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

它试图访问迭代器本身上的成员first,但失败了,因为它没有名为first的成员。如果是,那么您将取消引用该成员的值。


但是,在大多数这样的情况下,应该使用std::map从键映射到值。应该使用map<int,string>,而不是vector<pair<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;
}

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