我的简单代码是这样的:
#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”,第二对不能被带入容器中,即使这对对于第二对元素是不同的。
如何更改我的代码以完成工作?
std::set
宣布为:
template <class Key, class Compare = less<Key>,
class Allocator = allocator<Key> >
class set;
该集包含Key
类型的元素,使用第二个模板参数进行排序。所以你不能定义一个std::set< std::string, std::string >
来保存字符串对。
std::map
可用于存储成对的std::string
s,但钥匙是独一无二的。因此,您将无法使用相同的密钥(对的第一个元素)存储多个对。
如果你想存储对,你可以直接这样做,通过这样定义容器:
std::set< std::pair<std::string, std::string> > mySet;