簡體   English   中英

c++ 中的 Pairs 迭代器列表

[英]List of Pairs iterator in c++

#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);}的情況下顯示正確的值(2,4),這應該將迭代器帶到下一個頭,但它每次都顯示一些隨機值兩次。
  2. 錯誤:' std::__cxx11::list<std::pair<int, int> >::iterator ' {aka ' struct std::_List_iterator<std::pair<int, int> > '} 沒有命名成員' first ' cout<<*i.first;

您在這里調用未定義的行為

   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 !!

當指針指向數組中的元素時,您只能遞增指針以獲得有效指針。 將指針遞增到單個 object 很好,因為草率地說,一對可以被視為大小為 1 的數組,並且允許在數組的最后一個元素之后獲得一個指針。 但是,您不應取消引用該指針。

std::list不將其元素存儲在連續的 memory 中。 您可以在例如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});

此外,我建議您閱讀為什么我不應該#include <bits/stdc++.h> 為什么是“使用命名空間標准;” 被認為是不好的做法? .

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM