从对的向量中获取值时出错
Error in Getting Value from Vector of Pairs
在对向量的迭代器中访问对的值时,为什么会出现以下错误?
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;
}
请注意,映射和成对向量之间的一个本质区别是,映射通过按关键字对元素进行排序来重新排列元素。之后无法查询插入顺序。在某些情况下(当插入顺序很重要时),您不想这样做,因此在这种情况下,您的解决方案或具有至少包含键和值的自定义类型的向量是正确的解决方案。
相关文章:
- 使用boost库(cpp_int)时获取常量时出错
- 获取链接 创建flyweight_pattern时出错
- 在 Eclipse 中获取临时地址时出错
- 从源文件获取 ui 元素时出错
- 获取 ADC 输入时出错
- 想要从图像获取绿色 RGB 通道时出错
- 尝试从矢量获取unique_ptr元素后出错
- 获取应用程序的内存使用情况时出错
- 获取WinPcap地址信息时出错
- 迭代映射以获取输入时出错
- 从我的二维数组中设置和获取值时出错
- OpenCV在尝试从轴摄影机获取图像时出错
- C++在尝试编写对象读取器时,在尝试从一个向量获取数据时出错
- 在 C++ 中打开文件时出错:从字符串中获取字符时出错
- 在 OnDocumentComplete 中获取 iFrame 宽度和高度时出错
- 尝试从字符串中获取 int 时出错
- 当我尝试通过Qt在FTP上获取文件时出错
- 获取 html 代码时出错
- 获取POCO HTTPSClientSession发送请求时出错-证书验证失败
- c++ NetBeans在获取指针子向量中元素的字符串值时出错