【问题标题】:Error in Getting Value from Vector of Pairs从对向量中获取值时出错
【发布时间】:2013-01-31 03:47:51
【问题描述】:

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

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 >::iterator’没有名为‘first’的成员 main_v10.cpp:165:56: 错误:‘std::vector > >::iterator’没有名为‘second’的成员

我该如何解决这个问题?

【问题讨论】:

标签: c++ vector iterator


【解决方案1】:

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

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&lt;int,string&gt; 而不是 vector&lt;pair&lt;int,string&gt; &gt;,它的行为相似(插入、迭代和其他事情也发生在对上),但它对数据结构中的键进行排序以便更快地随机访问:

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

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

【讨论】:

  • 我认为第二个变种应该是(*it).first
猜你喜欢
  • 1970-01-01
  • 2014-07-13
  • 2016-03-15
  • 1970-01-01
  • 1970-01-01
  • 2021-11-27
  • 1970-01-01
  • 2023-04-09
  • 1970-01-01
相关资源
最近更新 更多