如何在stl中访问嵌套在另一对中的对的第二个元素? [英] How do I access second element of a pair nested in another pair in stl?

查看:61
本文介绍了如何在stl中访问嵌套在另一对中的对的第二个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的矢量:

vector<对< int,pair< int,int> > > v

我想访问所有这三个元素。我怎么能通过迭代器做到这一点?



我尝试过:



我在互联网上寻找可能的答案,但无法得到任何满意的答案。我试过像这样的迭代器:

vector<对< int,pair< int,int> > > v;

vector<对< int,pair< int,int> > > :: iterator it = v.begin();

cout<< it-> first-> second;

它不工作

I have a vector like this :
vector < pair < int, pair < int,int > > > v
I want to access all the three elements . How can i do that through iterator?

What I have tried:

I looked for the possible answers on the internet but cannot get any satisfactory answer. I tried iterator like this :
vector < pair < int,pair <int,int> > > v;
vector < pair < int,pair <int,int> > > :: iterator it=v.begin();
cout<<it->first->second;
Its not working

推荐答案

向量在其实现中只接受一个类型,因此您不能拥有< int,pair>。您需要创建一个新类,或使用一对也包含一对;类似于:

A vector only accepts one Type in its implementation, so you cannot have <int, pair>. You need to create a new class, or use a pair that also contains a pair; something like:
vector<pair<int, pair<int, int > > > v;
pair<int, int> p;
pair<int, pair< int, int> > q;
p.first = 1;
p.second = 2;
q.first = 1;
q.second = p;
v.push_back(q);

p.first = 3;
p.second = 4;
q.first = 2;
q.second = p;
v.push_back(q);
for (vector<pair<int, pair<int, int > > >::iterator it = v.begin(); it < v.end(); ++it)
{
    q = *it;
    int num = q.first;
    p = q.second;
    cout << num << " : " << p.first << " - " << p.second << endl;
}


这篇关于如何在stl中访问嵌套在另一对中的对的第二个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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