【问题标题】:How to insert a pair of elements as single elements in a set container?如何将一对元素作为单个元素插入到集合容器中?
【发布时间】:2013-09-06 11:10:00
【问题描述】:

我的简单代码是这样的:

#include<iostream>
#include<set>

using namespace std;

void main() {
     set<string,string> myset;
     myset.insert(pair<string,string>("abc","def"));
     cout<<myset.size()<<endl;
}

即我想把对作为集合元素。但是这段代码会产生错误。在地图容器中,我也面临插入不同对作为元素的困难。但在("abc","def")("abc","ghe") 的情况下,对于相同的键值,即“abc”,即使对的第二个元素不同,第二对也不能放入容器中。

如何更改我的代码以完成工作?

【问题讨论】:

    标签: c++ dictionary set containers std-pair


    【解决方案1】:

    std::set 声明为:

    template <class Key, class Compare = less<Key>,
              class Allocator = allocator<Key> >
        class set;
    

    该集合包含Key 类型的元素,使用第二个模板参数排序。所以你不能定义一个std::set&lt; std::string, std::string &gt; 来保存成对的字符串。

    std::map 可用于存储std::strings 对,但键是唯一的。因此,您将无法使用相同的键(该对的第一个元素)存储多个对。

    如果你想存储对,你可以直接这样做,通过像这样定义容器:

    std::set< std::pair<std::string, std::string> > mySet;
    

    【讨论】:

      猜你喜欢
      • 2018-04-04
      • 2011-10-19
      • 2019-03-10
      • 1970-01-01
      • 2011-10-28
      • 2023-04-03
      • 2011-05-30
      • 2023-03-31
      相关资源
      最近更新 更多