如何在 stl 中的向量中访问嵌套在对内的对元素

How to access pair elements nested inside pair in a vector in stl

本文关键字:元素 嵌套 访问 向量 stl      更新时间:2023-10-16

我有一个这样的向量:

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

我想访问所有三个元素。如何通过迭代器执行此操作?我在下面将迭代器声明为 it1 和 it2:

#include <bits/stdc++.h>
using namespace std;
int main() 
{
int t;
scanf("%d",&t);
while(t--)
{
    vector<pair<int,pair<int,int> > > v;
    int n,a,b,i;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        scanf("%d%d",&a,&b);
        v.push_back(make_pair(b,make_pair(a,i+1)));
    }
    sort(v.begin(),v.end());
    vector<pair<int,pair<int,int> > > :: iterator it1=v.begin();
    vector<pair<int,pair<int,int> > > :: iterator it2=v.begin()+1;
    printf("%d ",(it1->first)->second);
        while(it2!=v.end())
        {
            if(it2->first.first>it1.first)
            {
                printf("%d ",it2.first.second);
                it1=it2;
            }
            it2++;
        }
    }
   return 0;
}

遵循类型。

如果it是一个迭代器结束

vector<pair<int, pair<int, int>>> 

那么*it是一个

pair<int, pair<int, int>>  

所以it->first(又名 (*it).first)是intit->secondpair<int,int>

这意味着您的元素是

it->first
it->second.first
it->second.second
 //  It may help you !!!
 vector < pair < int , pair < int, int > > > v;
 vector < pair < int , pair < int, int > > > ::iterator it;
 for(int i=1; i<=5; i++)
 {
     v.push_back(make_pair(i,make_pair(i+5,i+10)));
 }
 for(it= v.begin(); it!= v.end(); it++)
 {
     cout << it->first << " " << it->second.first << " " << it->second.second <<endl;
 }
// first element access  : it->first;
// second element access : it->second.first;
// Third element access  : it->second.second;

假设你有一个迭代器it你可以这样做:

std::cout << "first int: " << it->first << " first nested int: " << it->second.first << " second nested int: " << it->second.second;