unique_ptr 的 C++ 嵌套映射
C++ nested map with unique_ptr
我目前正在学习 C++ 并专注于 STL。我没有找到这个问题的答案,所以问题来了:如何在数据结构map<int, map<string, vector<unique_ptr>>>
中设置元素?以下带有一些注释的代码说明了这个问题:
#include <map>
#include <string>
#include <memory>
#include <vector>
using namespace std;
// Used in the example
struct Resource {};
int main(int argc, char** argv) {
// I was able to get the following map running fine
// int -> { string -> unique_ptr }
map<int, map<string, unique_ptr<Resource>>> data;
map<string, unique_ptr<Resource>> toBeInserted;
toBeInserted["key"] = unique_ptr<Resource>(new Resource);
// data[1] = toBeInserted; // error
data[1] = std::move(toBeInserted); // ok
// But the issue happens when it's a vector of unique_ptrs
// int -> { string -> { [unique_ptr] } }
map<int, map<string, vector<unique_ptr<Resource>>>> otherData;
vector<unique_ptr<Resource>> list;
list.push_back(unique_ptr<Resource>(new Resource));
list.push_back(unique_ptr<Resource>(new Resource));
map<string, vector<unique_ptr<Resource>>> _toBeInserted;
_toBeInserted["key"] = std::move(list); // ok
// But I cant insert _toBeInserted back to the original map.
// The compilation errors are all related to the unique_ptr
otherData[1] = std::move(_toBeInserted); // Can't do this
}
-- 编辑:link 到编译错误:ideone.com/hs3G8m
我的问题是如何初始化和添加元素到结构map<int, map<string, vector<unique_ptr<T>>>>
。我正在使用带有 c++11 标志的 GCC 4.9。提前致谢!
我没有发现代码有任何问题。
我将其编译为
g++ -Wall -std=c++11 test.cpp
使用 gcc (GCC) 4.8.1
没有任何警告
它看起来像一个 compiler/STL 错误。
我目前正在学习 C++ 并专注于 STL。我没有找到这个问题的答案,所以问题来了:如何在数据结构map<int, map<string, vector<unique_ptr>>>
中设置元素?以下带有一些注释的代码说明了这个问题:
#include <map>
#include <string>
#include <memory>
#include <vector>
using namespace std;
// Used in the example
struct Resource {};
int main(int argc, char** argv) {
// I was able to get the following map running fine
// int -> { string -> unique_ptr }
map<int, map<string, unique_ptr<Resource>>> data;
map<string, unique_ptr<Resource>> toBeInserted;
toBeInserted["key"] = unique_ptr<Resource>(new Resource);
// data[1] = toBeInserted; // error
data[1] = std::move(toBeInserted); // ok
// But the issue happens when it's a vector of unique_ptrs
// int -> { string -> { [unique_ptr] } }
map<int, map<string, vector<unique_ptr<Resource>>>> otherData;
vector<unique_ptr<Resource>> list;
list.push_back(unique_ptr<Resource>(new Resource));
list.push_back(unique_ptr<Resource>(new Resource));
map<string, vector<unique_ptr<Resource>>> _toBeInserted;
_toBeInserted["key"] = std::move(list); // ok
// But I cant insert _toBeInserted back to the original map.
// The compilation errors are all related to the unique_ptr
otherData[1] = std::move(_toBeInserted); // Can't do this
}
-- 编辑:link 到编译错误:ideone.com/hs3G8m
我的问题是如何初始化和添加元素到结构map<int, map<string, vector<unique_ptr<T>>>>
。我正在使用带有 c++11 标志的 GCC 4.9。提前致谢!
我没有发现代码有任何问题。 我将其编译为
g++ -Wall -std=c++11 test.cpp使用
gcc (GCC) 4.8.1没有任何警告
它看起来像一个 compiler/STL 错误。