如何打印类型为vector <pair <char,int>屏幕C ++? [英] How to print a type vector&lt;pair&lt;char, int&gt;&gt; to screen c++?

查看:394
本文介绍了如何打印类型为vector <pair <char,int>屏幕C ++?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个返回值向量的方法>,我不知道如何打印该向量的内容。我试图遍历所有内容,但出现编译器错误。这是我尝试过的示例。

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
}


推荐答案

std :: pair 第一第二数据成员,因此对循环的琐碎修改将打印出内容:

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

在C ++ 11中,元素也可以访问元组样式,通过 std :: get

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;

在C ++ 11中,您还可以选择使用基于范围的循环遍历所有对象容器的元素:

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

这篇关于如何打印类型为vector <pair <char,int>屏幕C ++?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆