How to print a type vector<pair<char, int>> to screen c++?
Asked Answered
C

2

16

I have a method that returns a value vector> and I cannot figure out how to print the contents of this vector. I was trying to loop through the contents but I get compiler errors. Here is an example of what I have tried.

vector<pair<char, int>> output;

for(int i = 0; i < ouput.size; i++)
{
     cout << output[i][i] << endl; //output[i][i] does no work: no operator [] matches these operands
}
Caliban answered 7/10, 2013 at 15:42 Comment(0)
G
31

The elements of an std::pair are the first and second data members, so a trivial modification of your loop would print out the contents:

for(int i = 0; i < output.size(); i++)
{
     cout << output[i].first << ", " << output[i].second << endl;
}

In C++11, the elements are also accessible tuple-style, via std::get,

     cout << std::get<0>(output[i]) << ", " << std::get<1>(output[i]) << endl;

In C++11, you also have the option of using a range based loop to iterate over all the elements of a container:

for (const auto& p : output)
{
  std::cout << p.first << ", " << p.second << std::endl;
  // or std::cout << std::get<0>(p) << ", " << std::get<1>(p) << std::endl;
}
Gurtner answered 7/10, 2013 at 15:43 Comment(2)
I keep getting a compiler error Error 2 error C2678: binary '==' : no operator found which takes a left-hand operand of type 'std::pair<char,int>' (or there is no acceptable conversion) c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility 3026 1 CptS427_PA1_CaesarCypherCaliban
@Caliban you must be missing a header include somewhere.Gurtner
B
9
vector<pair<char, int>> output;

for(int i = 0; i < ouput.size (); i++)
{
     cout << output[i].first << ":" << output[i].second<< endl; 
}

With C++11 :

for(auto &x:output)
{
  cout<<x.first<<":"<<x.second<<std::endl;
}
Baldheaded answered 7/10, 2013 at 15:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.