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

时间:2017-06-16 11:34:06

标签: c++ stl

我有一对对矢量

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++)

4 个答案:

答案 0 :(得分:2)

提供了任何代码,以便我们能够知道您的计算机出了什么问题。 但这是一个关于如何访问对矢量的工作示例:

this.$refs.dob.showCalendar()

输出,see here

#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;
}

编辑#1:

现在您提供代码,但实际上您正在使用对的向量数组:First: 1, Second: One First: 2, Second: Two First: 3, Second: Three 。您还可以将vector <pair<int,int> > a[4];方法中的iterator放入begin()。看来你混合了很多东西,比如说这里[] operator(一个i=a[i].begin()是迭代器,另一个是索引)并且不明白它们的真正含义。请查看我的示例并阅读有关数组和向量以及如何正确访问它们的信息。另请阅读有关索引和基于迭代器的访问的区别。

编辑#2:

这个循环:

i

应该是:

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; } } ,所以我将其用作最大值。

答案 1 :(得分: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";
}

答案 2 :(得分:0)

using System.Linq;

...         

Console.WriteLine("enter number separated by comma ");

List<int> userDecision = Console
  .ReadLine()
  .Split(',')
  .Select(item => (success : int.TryParse(item, out int value), 
                     input : value))
  .Where(record => record.success && 
                  (record.input == -1 || record.input >= 1 && record.input <= 4))
  .Select(record => record.input)
  .ToList();     

答案 3 :(得分:0)

我在一个问题中使用了这个概念,您可以查看执行您想要的相同功能的代码

polygons