为什么在对 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!
}
错误信息:
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’
我该如何解决这个问题?
最佳答案
这个问题也适用于指针(迭代器的行为非常像指针)。有两种方法可以访问指针(或迭代器)指向的值的成员:
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
从键映射到值。而不是 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;
}
请注意, map 和成对 vector 之间的本质区别在于, map 通过按元素的键对元素进行排序来重新排列元素。之后无法查询插入顺序。在某些情况下您不想这样做(当插入顺序很重要时),因此在这种情况下,您的解决方案或具有至少包含键和值的自定义类型的 vector 是正确的解决方案。
关于c++ - 从成对 vector 中获取值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14890130/