【问题标题】:How to print out elements of multiset of pair如何打印出多组对的元素
【发布时间】:2018-04-09 20:27:46
【问题描述】:
multiset< pair<int,pair<int,int>> >ml;
pair<int,pair<int,int>> p;
p.first=3;
p.second.first=5;
p.second.second=2;
ml.insert(p);

这就是我在我的多对中插入的方式 但我不知道如何打印出我的多对中的所有元素 我试过了,但它不起作用

 multiset< pair<long long,pair<long long,long long> > >::iterator it;
      it=ml.begin(); 
   p=*it;
cout<<p.first<<" "<<p.second.first<<" "<<p.second.second<<endl;

【问题讨论】:

标签: c++ c++11 stl multiset


【解决方案1】:

只需遍历集合(C++11 基于范围的 for 在这里很好):

for (auto x : ml)
{
    cout << "First: " << x.first <<" " << " Second first: " << x.second.first << " Second.second: " << x.second.second << endl;
}

【讨论】:

    【解决方案2】:

    有两种方法。它们几乎相同,但第二个要短得多。

    第一种方法:

    for (multiset< pair<int, pair<int,int> > >::iterator it = ml.begin(); it!=ml.end(); it++) {
        cout<<"First: "<<it->first<<", Second: "<<it->second.first<<", Third: "<<it->second.second<<endl;
    }
    

    第二种方法(仅在 C++11 及更高版本中):

    for (auto it:ml) {
        cout<<"First: "<<it.first<<", Second: "<<it.second.first<<", Third: "<<it.second.second<<endl;
    }
    

    而且输出是一样的:

    First: 3, Second: 5, Third: 2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-16
      • 2019-07-22
      • 2017-11-19
      • 1970-01-01
      • 2020-04-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多