【发布时间】:2014-01-11 07:11:46
【问题描述】:
将记录类型映射到字段值向量:
unordered_map<string, vector<string>> input_records;
string rec_type {"name"};
vector<string> fields { "field 1", "field 2", "field 3" };
我想将fields 复制到input_records[rec_type]。以下不起作用:
_input_records[rec_type].insert(rec_deq.begin(), rec_deq.end());
然而 unordered_map 的 boost 文档包含以下内容:
template<typename InputIterator>
void insert(InputIterator first, InputIterator last);
Inserts a range of elements into the container. Elements are inserted if and only if there is no element in the container with an equivalent key.
Throws:
When inserting a single element, if an exception is thrown by an operation other than a call to hasher the function has no effect.
Notes:
Can invalidate iterators, but only if the insert causes the load factor to be greater to or equal to the maximum load factor.
Pointers and references to elements are never invalidated.
(写到这里,我意识到 InputIterator 可能指向一个键/值对序列,每个键/值对都将被插入到 Map 中。所以,错误的方法。)
如何最好地实例化和填充input_record[rec_type] 处的向量?一旦填充,向量将不会被修改。像input_record[rec_type] = fields这么简单吗?在这种情况下是否或可以应用“移动语义”?
【问题讨论】:
-
"像
input_record[rec_type] = fields这么简单吗?"你试过了吗? ;-o 对于移动语义,将fields替换为临时的(在 C++11 中更容易)。 “放置”新值比移动它稍好一些,但考虑到您的数据类型,它不太可能很重要。
标签: boost c++11 vector unordered-map