如何打印成对矢量数组的元素?

问题描述 投票:-8回答:2

我有一对矢量对

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

我已经使用push_back添加了元素。但是我不知道如何打印元素。如果我使用一个iteretor并打印它像[i] .first或[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});
}

这就是我推送元素的方法。但是如何打印它们。

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

我收到以下错误。我不知道如何打印它们。

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++)
c++ stl
2个回答
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];。此外,你把iterator方法中的begin()放入[] 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
投票
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";
}
© www.soinside.com 2019 - 2024. All rights reserved.