微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C++ 中的 Pairs 迭代器列表

如何解决C++ 中的 Pairs 迭代器列表

#include <bits/stdc++.h>
using namespace std;

int main() {
    unordered_map< int,list<pair<int,int>>> adjList;
    adjList[1].push_back(make_pair(2,2));
    adjList[1].push_back(make_pair(4,-1));
    adjList[0].push_back(make_pair(1,3));
    for(pair<int,int> neighbour : adjList[1]){
        pair<int,int>* it = &neighbour;
       std::advance (it,1);
       cout<<it->first<<" ";    //1)showing random value twice instead of 4(-1113715584 -1113715584) 
    }
    for (list<pair<int,int>>::iterator i=adjList[1].begin(); i!=adjList[1].end(); i++)
        cout<<*i.first;         //2)list<std::pair<int,int> >::iterator'has no member named 'first'
    }
}
  1. 它在没有 {std::advance (it,1);} 的情况下显示正确的 value(2,4),它应该将迭代器带到下一个头,但它每次都显示一些随机值两次。
  2. 错误:'std::__cxx11::list<std::pair<int,int> >::iterator' {aka 'struct std::_List_iterator<std::pair<int,int> >'} 没有名为 'first' 的成员 cout<<*i.first;

解决方法

您在此处调用 undefined beahvior

   pair<int,int>* it = &neighbour;
   std::advance (it,1);
   cout<<it->first<<" ";

一样的问题
   std::pair<int,int> p;
   std::pair<int,int>* ptr = &p;
   ptr += 1;                     // ok-ish 
   std::cout << ptr->first;      // undefined behavior !!

当指针指向数组中的元素时,您只能递增指针以获得有效指针。将指向单个对象的指针递增是可以的,因为草率地说,一对可以被视为大小为 1 的数组,并且允许在数组的最后一个元素之后获取指针。但是,您不应取消引用该指针。

A std::list 不会将其元素存储在连续内存中。您可以在例如 std::vector 中获取指向元素的指针,然后将其推进以获取指向下一个元素的指针。但是,您所取的地址实际上不是列表中的元素。当你写

for(pair<int,int> neighbour : adjList[1]){

那么 neighbour 是列表中元素的副本。它是一个单独的 pair,与 list 完全无关。如果你曾经使用过

for(pair<int,int>& neighbour : adjList[1]){

那么 neighbour 将是对列表中元素的引用,但由于上述原因,您的代码仍然会出错。


第二个错误是由于打字错误。 *i.first*(i.first),但您想要 (*i).firsti->first


最后但并非最不重要的一点是,考虑到 std::make_pair 的用例比 C++11 之前少得多。您的案例不是其中之一,您可以简单地写:

adjList[1].push_back({2,2});

此外,我建议您阅读Why should I not #include <bits/stdc++.h>?Why is “using namespace std;” considered bad practice?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。