我目前正在学习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
}
-- 编辑:编译错误链接:ideone.com/hs3G8m
我的问题是如何初始化并向结构体map<int, map<string, vector<unique_ptr<T>>>>
中添加元素。我正在使用带有c++11标志的GCC 4.9。提前感谢!
vector<unique_ptr<Resource>> list;
建议不要将变量命名为STL类的名称,例如list
。 - PaulMcKenzieunique_ptr
?如果你将一个unique_ptr
放入一个vector
中,那么当你想要解引用它时,你必须先将其移出,因为你不允许制作重复的副本。看起来shared_ptr
是你尝试实现的适当类型。 - Saran Tunyasuvunakoolclang++
似乎正在使用GCC的STL。在Mac OS X上,OP的代码实际上可以使用-std=c++11
在clang++
和Intel的icpc
上编译通过。这两个都使用Clang的STL。看起来像是GCC的STL中的一个错误?(另外,我收回了关于此处unique_ptr
有效性的评论:只要OP在从map
中取出指针时不尝试“别名”它,就可以使用) - Saran Tunyasuvunakool