C++ 如何在stl中访问向量中嵌套在对内的对元素
我有一个像这样的向量:C++ 如何在stl中访问向量中嵌套在对内的对元素,c++,stl,C++,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<
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;
}
假设您有一个迭代器,您可以这样做:
std::cout << "first int: " << it->first << " first nested int: " << it->second.first << " second nested int: " << it->second.second;
遵循类型
如果它是
vector<pair<int, pair<int, int>>>
所以it->first a.k.a.*it.first是一个int,it->second是一对
这意味着您的元素是
it->first
it->second.first
it->second.second
您是否尝试过:v[index].second.first和v[index].second.second?如果使用C++ 11,也可以考虑使用元组。到处都是。在某些地方使用正确的运算符,在另一些地方则不使用。您的代码非常不一致。欢迎使用堆栈溢出,请查看:感谢您提供此代码段,它可能会提供一些有限的即时帮助。通过展示为什么这是一个很好的问题解决方案,A将极大地提高它的长期价值,并将使它对未来有其他类似问题的读者更有用。请在您的回答中添加一些解释,包括您所做的假设。
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;