zer*_*0ne 3 c++ stl unique-ptr
我有一个字段定义为
const vector<record>* data;
Run Code Online (Sandbox Code Playgroud)
其中记录定义为
const unique_ptr<vector<float>> features;
const float label;
Run Code Online (Sandbox Code Playgroud)
在我的主要代码中,我使用
vector<record>::iterator iter = data->begin()
Run Code Online (Sandbox Code Playgroud)
编译器对我的代码不满意,在迭代器分配行没有可行的重载'='错误.它还会产生此警告:
/Library/Developer/CommandLineTools/usr/bin/../include/c++/v1/iterator:1097:7: note: candidate function (the implicit copy assignment operator) not viable: no known conversion from '__wrap_iter<const_pointer>' to 'const __wrap_iter<class MLx::Example *>' for 1st argument
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
"迭代器应该是轻量级的,现在应该拥有数据,即在进行分配时不应该尝试复制甚至触摸记录."
它与迭代器无关,将拥有存储在数据中的数据data,但是const unique_ptr<>,仅限制作为const实例访问模板参数类型.
这意味着你需要使用
vector<record>::const_iterator iter = data->begin();
// ^^^^^^
Run Code Online (Sandbox Code Playgroud)
在你的主要代码中.
这很像写作
const vector<record>* data;
Run Code Online (Sandbox Code Playgroud)
正如@Jonathan Potter在评论中提到的那样
auto iter = data->begin();
Run Code Online (Sandbox Code Playgroud)
也应该工作.