2017-06-16 50 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"; 
}