使用带有自定义构造函数的std :: set自定义比较器

洪bert

假设我有一堂课

class Custom
{
public:
    Custom (int x, int y) : x (x), y (x) {} 
    bool operator() (int a, int b)
    {
        return a < x && y < b;
    }
private:
    int x, y;
};

我想要一套

std::set<int, Custom> s 

使用Custom的自定义构造函数(即Custom(1、2))

我该如何实现?

另外,如果我想在unordered_map中使用它,例如

std::unordered_map<string, std::set<int, Custom>> ht

我怎样才能做到这一点?

J·安东尼奥·佩雷斯

进行设定

构造集合时,需要提供比较器:

using std::unordered_map;
using std::set; 
using std::string; 

set<int, Custom> s(Custom(10, 20)); 
// Or: 
auto s = set<int, Custom>(Custom(10, 20)); 

这是因为在开始将元素分配给集合时,它需要有一个比较器,并且由于比较器具有参数,因此它需要知道这些参数是什么。

在地图中使用场景

比较器必须是默认可构造的,因为map["key"]如果元素不存在,则调用将默认构造该元素:

class Custom
{
   public:
    // Add a default constructor
    Custom() : x(0), y(0) {}
    Custom (int x, int y) : x (x), y (x) {} 
    bool operator() (int a, int b)
    {
        return a < x && y < b;
    }
   private:
    int x, y;
};

在这种情况下,可以为比较器提供默认的构造函数,因为我们可以重新分配它:

unordered_map<string, set<int, Custom>> map; 
map["some key"] = set<int, Custom>(Custom(10, 20)); 

如果没有默认构造函数怎么办?

我们仍然可以使用unordered_map,但是我们必须使用map.at("key")map.emplace("key", value)而不是map["key"]

unordered_map<string, set<int, Custom>> map; 
set<int, Custom> s(Custom(10, 20)); 
set<int, Custom> s2(Cunstom(30, 40)); 
s2.insert(1);
s2.insert(2); 
s2.insert(3); // put some stuff in the set

map.emplace("Hello", s); //Inserts the set

map.insert({"Hello", s2}); //Inserts the set as a key-value pair

我们可以使用map.at以下方法获取值

// This line gets the set at "Hello", and inserts 10 into the set:
map.at("Hello").insert(10); 
// If "Hello" isn't in the map, there's an error

我们可以使用来检查地图中是否有东西map.find("key")

// Get an iterator to the key value pair held by "Hello" in the map:
// An iterator acts like a pointer
auto iterator = map.find("Hello"); 

if(iterator == map.end()) // Check if we found the thing
{
    std::cout << "Couldn't find 'Hello' in the map"; 
} 
else 
{
    // Get the key from the iterator
    string key = iterator->first; 
    // Get a reference to the value from the iterator
    set<int, Custom>& value = iterator->second; 

}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章