如何打印类型 vector<pair<char, int>> 来筛选 C++?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19228994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to print a type vector<pair<char, int>> to screen c++?
提问by user977154
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> 的方法,但我不知道如何打印这个向量的内容。我试图遍历内容,但出现编译器错误。这是我尝试过的一个例子。
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
}
回答by juanchopanza
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:
an 的元素std::pair
是first
andsecond
数据成员,因此对循环进行微不足道的修改将打印出内容:
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
,
在 C++11 中,元素也是可访问的,tuple
样式,通过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:
在 C++11 中,您还可以选择使用基于范围的循环来迭代容器的所有元素:
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;
}
回答by P0W
vector<pair<char, int>> output;
for(int i = 0; i < ouput.size (); i++)
{
cout << output[i].first << ":" << output[i].second<< endl;
}
With C++11 :
使用 C++11 :
for(auto &x:output)
{
cout<<x.first<<":"<<x.second<<std::endl;
}