2017-06-16 55 views
-8

我有對如何打印成對向量數組的元素?

vector <pair<int,int> > a[4] 

.I的矢量的陣列已經添加元素使用它push_back.But我不知道如何打印我使用iteretor的elements.if和打印像[I]至.first或a [i] .second它會引發錯誤。執行此操作的其他方法。提前感謝。

vector <pair<int,int> > a[4]; 
for(int i = 0;i < e;++i) 
{ 
    int x,y; 
    cin >> x >> y >> w; 
    a[x].push_back({w, y}); 
    a[y].push_back({w, x}); 
} 

這是我如何推送elements.But如何打印它們。

for(i=a[i].begin();i!=a[i].end();i++) 
{ 
    cout<<a[i].second<<" "; 
} 

我正在以下error.I硝基甲苯知道如何打印。

error: no match for 'operator[]' (operand types are 'std::vector<std::pair<int, int> >*' and 'std::vector<std::pair<int, int> >::iterator {aka __gnu_cxx::__normal_iterator<std::pair<int, int>*, std::vector<std::pair<int, int> > >}') 
    for(i=g[i].begin();i!=g[i].end();i++) 
+0

歡迎來到Stack Overflow。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –

+0

爲什麼這是我不應該問的話題? – piku

+0

你確定要有一個'vector >'的數組嗎? –

回答

2

你做提供任何代碼,使我們可以能夠知道你的機器什麼錯。 但這裏是關於如何訪問對的矢量工作的例子:

#include <utility> 
#include <iostream> 
#include <vector> 
#include <string> 

typedef std::pair<int, std::string> pairIntString; 
int main() 
{ 
    std::vector<pairIntString> pairVec; 

    pairVec.push_back(std::make_pair(1, "One")); 
    pairVec.push_back(std::make_pair(2, "Two")); 
    pairVec.push_back(std::make_pair(3, "Three")); 

    for (std::vector<pairIntString>::const_iterator iter = pairVec.begin(); 
     iter != pairVec.end(); 
     ++iter) 
    { 
     std::cout << "First: " << iter->first 
       << ", Second: " << iter->second <<std::endl; 
    } 
    return 0; 
} 

輸出,see here

First: 1, Second: One 
First: 2, Second: Two 
First: 3, Second: Three 

編輯#1:

現在你提供的代碼,但您實際上正在使用一組向量對:vector <pair<int,int> > a[4];。此外,您將begin()方法中的iterator放入[] operator。看起來你混合了很多東西,例如這裏i=a[i].begin()(其中一個i是迭代器,另一個是索引)並且不明白它們的真正用途。請看我的示例並閱讀有關數組和向量以及如何正確訪問它們的內容。還要了解基於索引和基於迭代器的訪問的區別。

編輯#2:

這個循環:

for(i=a[i].begin();i!=a[i].end();i++) 
{ 
    cout<<a[i].second<<" "; 
} 

也許應該是:

/* loop through the fixed size array */ 
for(size_t idx = 0; idx < 4; ++i) 
{ 
    cout << "Array element idx: " << idx << endl; 
    /* get the iterator of the specific array element */ 
    for (vector <pair<int,int> >::const_iterator iter = a[idx].begin(); 
     iter != a[idx].end(); 
     ++iter) 
    { 
     cout << "First: " << iter->first 
      << ", Second: " << iter->second << endl; 
    } 
} 

你遇到對的向量的數組你有兩個循環在數組和向量上。由於陣列的固定尺寸爲4,所以我將其用作最大值。

+0

我已經在我的post.How打印這種情況下 – piku

+0

不,我需要it.i需要使用它的鄰接表representation.can你告訴我如何打印元素 – piku

+0

雅我是新的使用stl在c + +中這就是爲什麼這些混亂。 – piku

0
vector <pair<int,int>> vec[5]; 
vector <pair<int,int>> :: iterator it; 

for(int i=0;i<5;i++){ 
    for(it=vec[i].begin(); it!=vec[i].end();it++) cout << it->first << " " << it->second << " -> "; 
    cout << "\n"; 
}