相关疑难解决方法(0)

std :: map emplace没有复制值

C++ 11 std::map<K,V>类型具有一个emplace函数,许多其他容器也是如此.

std::map<int,std::string> m;

std::string val {"hello"};

m.emplace(1, val);
Run Code Online (Sandbox Code Playgroud)

此代码的工作方式与宣传的一样,std::pair<K,V>直接安排,但它会产生副本keyval发生.

是否可以将值类型直接置于地图中?我们能比调用中的参数更好emplace吗?


这是一个更彻底的例子:

struct Foo
{
   Foo(double d, string s) {}
   Foo(const Foo&) = delete;
   Foo(Foo&&) = delete;
}

map<int,Foo> m;
m.emplace(1, 2.3, string("hello")); // invalid
Run Code Online (Sandbox Code Playgroud)

c++ dictionary stl c++11 emplace

48
推荐指数
2
解决办法
2万
查看次数

使用std :: pair作为键创建std :: unordered_map

我正在尝试使用std :: pair作为键创建一个std :: unordered_map.可以想象,这需要我明确地提供一个类来为给定的密钥生成哈希,以及密钥的相等比较器.到目前为止,这是我的代码:

#include <unordered_map>
#include <memory>
#include <utility>

template <class T, typename U> 
struct PairHash{ 
    size_t operator()(const std::pair<T, U> &key){ 
        return std::hash<T>()(key.first) ^ std::hash<U>()(key.second);
    }
};

template <class T, typename U>
struct PairEqual{
    bool operator()(const std::pair<T, U> &lhs, const std::pair<T, U> &rhs) const{
        return lhs.first == rhs.first && lhs.second == rhs.second;
    }
};

struct GraphEdge{

};


int main(){

    std::unordered_map<std::pair<int, int>, 
                       std::unique_ptr<GraphEdge>, 
                       PairHash<int, int>,
                       PairEqual<int, int>>  edges; 

}
Run Code Online (Sandbox Code Playgroud)

但是,这给了我一个(至少我的眼睛)不可思议的编译器错误:

In file included from /usr/include/c++/5/bits/hashtable.h:35:0,
                 from /usr/include/c++/5/unordered_map:47,
                 from prog.cpp:1: …
Run Code Online (Sandbox Code Playgroud)

c++ c++11

16
推荐指数
1
解决办法
9397
查看次数

标签 统计

c++ ×2

c++11 ×2

dictionary ×1

emplace ×1

stl ×1