如何在 stl 中的向量中访问嵌套在对内的对元素
How to access pair elements nested inside pair in a vector in stl
我有一个这样的向量:
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
)是int
,it->second
是pair<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;
相关文章:
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 不能使用嵌套结构中的联合元素作为 scanf() 的参数来存储所需的值
- 访问range_expression中的嵌套元素会返回不完整的映射(段错误)
- 删除嵌套向量中具有remove_if的元素
- 在循环访问嵌套向量时删除元素
- 为什么 OpenCL 嵌套循环仅适用于某些元素
- 嵌套的C 常数数据结构,没有初始化列表或明确命名所有节点-VC 2012过早破坏了内部元素
- C 无法使用嵌套环将数组的元素索引
- C++嵌套的带有擦除元素的循环
- 在嵌套向量C 中获取特定元素
- 标记元素C 阵列带嵌套循环
- 如何访问嵌套的stl元素
- 将xml字符串嵌套到xml元素中的语法
- C++ -- 使用嵌套类中的类元素?
- 解码元素的嵌套列表时使用ei_decode_list
- 如何在嵌套向量中获取元素类型
- 如何使用 qt 删除嵌套的 xml 元素
- 从向量生成元素的子集(无嵌套循环)
- 如何擦除嵌套在矢量中的列表中的元素
- 如何添加元素到嵌套向量