C++ 从对的向量中获取值时出错
在对向量的迭代器中访问对的值时,为什么会出现以下错误C++ 从对的向量中获取值时出错,c++,vector,iterator,C++,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();
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!
}
向量映射器;
if(散列(输入,chordSize)!=id){
映射器。推回(生成映射对(tmp,输入));
}
对于(vector::迭代器it=mapper.begin();it!=mapper.end();+it)
{
cout这也是一个适用于指针的问题(迭代器的行为与指针非常相似)。有两种方法可以访问指针(或迭代器)指向的值的成员:
it->first // preferred syntax: access member of the pointed-to object
或
运算符优先级将表达式转换为
*(it.first) // wrong! tries to access a member of the pointer (iterator) itself
它尝试访问迭代器本身上的成员first
,但失败了,因为它没有名为first
的成员。如果有,则取消引用该成员的值
但是,在大多数情况下,您应该使用std::map
从键映射到值。您应该使用行为类似的map
,而不是vector
,但它在数据结构中对键进行排序以实现更快的随机访问:
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;
}
地图制图器;
if(散列(输入,chordSize)!=id){
映射器。推回(生成映射对(tmp,输入));
}
对于(map::iterator it=mapper.begin();it!=mapper.end();++it)
{
我想第二个变量应该是(*it)。首先,您可能需要读取运算符优先级,签出*
和
优先级:
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;
}