我有一段代码,在vector
中,元素是int
和string
对。然后我想将所有元素从vector
移到unordered_map<int, string>
:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <unordered_map>
#include <vector>
using namespace std;
template <typename C>
void print(const C& container) {
for (const auto& ele : container) {
cout << "(" << ele.first << ", " << ele.second << "), ";
}
cout << endl;
}
int main() {
vector<pair<int, string>> v {
{1, "one"},
{2, "two"},
{3, "three"},
{4, "four"},
{5, "five"}
};
unordered_map<int, string> uMap;
move(begin(v), end(v), inserter(uMap, begin(uMap)));
cout << "In unordered_map:" << endl;
print(uMap);
cout << endl << "In vector:" << endl;
print(v);
return 0;
}
我不了解结果:
In unordered_map:
(5, five), (4, four), (3, three), (2, two), (1, one),
In vector:
(1, ), (2, ), (3, ), (4, ), (5, ),
为什么这些整数保留在vector
中?我以为move()
函数会将所有元素从vector
移到unordered_map
,所以vector
中什么也不会剩下?
来自cppreference:
非正式地讲,对移出物体的唯一要求是,以后可以安全地销毁它。对于int
,最好的办法是什么也不做。移动不会破坏对象,也不会从容器中将其删除。这些对象仍然在矢量中,只是它们现在处于从移出状态,对于int
,它恰好与以前相同。