【问题标题】:How to access pair elements nested inside pair in a vector in stl如何在stl的向量中访问嵌套在pair内的pair元素
【发布时间】:2016-07-06 11:26:14
【问题描述】:

我有一个这样的向量:

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

【问题讨论】:

  • 你试过:v[index].second.firstv[index].second.second?还可以考虑使用元组(如果您使用的是 c++11)。
  • 您在到处混用对象访问运算符.-&gt;。在某些地方您使用正确的运算符,而在其他地方则没有。你很矛盾。

标签: c++ stl


【解决方案1】:

按照类型。

如果it 是一个迭代器

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

那么*it是一个

pair<int, pair<int, int>>  

所以it-&gt;first(又名(*it).first)是intit-&gt;secondpair&lt;int,int&gt;

这意味着你的元素是

it->first
it->second.first
it->second.second

【讨论】:

    【解决方案2】:
     //  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;
    

    【讨论】:

    • 欢迎来到 Stack Overflow,请查看:stackoverflow.com/help/how-to-answer
    • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
    【解决方案3】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多