使用emplace_back就地构造

 
    如果需要使用emplace_xx 来就地构造,则需要提供类或者结构体的构造函数。

struct A{
    int a;
    int b;
    A(int x, int y):a(x), b(y){};
};
int main(){
    vector<A> v;
    v.emplace_back(1,2);            //就地构造,需要结构体或类提供构造函数
    cout << v.size() << endl;
    return 0;
}

 

使用unordered container无序容器

 
    由于无序容器内部使用散列表,因此无序容器的key需要提供hash_value 函数,其他用法和map/set相同,对于自定义的key,需要提供hash函数和比较函数

struct Key{
    std::string first;
    std::string second;
};
struct KeyHash{
    std::size_t operator()(const Key& k)const{
        return std::hash<std::string>()(k.first)^(std::hash<std::string>()(k.second) << 1);
    };
};
struct KeyEqual{
    bool operator()(const Key& k1, const Key& k2){
        return k1.first == k2.first && k1.second == k2.second;
    }
};
int main(){
    std::unordered_map<std::string, int> m1;
    decltype(m1) m2 = {{"hello", 1}, {"world", 2}};
    
    std::unordered_map<Key, std::string, KeyHash, KeyEqual> m6 = {
    {{"john", "doe"}, "example"},
    {{"mary, "sue"}, "another"}}; //自定义类型的key,需要提供hash函数和比较函数
    return 0;
};

 

+

相关文章:

  • 2021-05-26
  • 2021-11-15
  • 2021-04-22
  • 2021-11-22
  • 2021-05-28
  • 2022-12-23
  • 2022-01-30
  • 2021-07-07
猜你喜欢
  • 2021-09-11
  • 2021-09-18
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-09
  • 2022-12-23
相关资源
相似解决方案