Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/wcf/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 从对的向量中获取值时出错_C++_Vector_Iterator - Fatal编程技术网

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