gpt4 book ai didi

C++ move () : what's left in the vector?

转载 作者:行者123 更新时间:2023-12-01 15:06:34 25 4
gpt4 key购买 nike

我有一段代码,在 vector 中, 元素是成对的 intstring .然后我想从 vector move 所有元素进入 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 move 所有元素进入unordered_map , 这样 vector 中就不会留下任何东西了?

最佳答案

来自 cppreference :

Moves the elements in the range [first, last), to another range beginning at d_first, starting from first and proceeding to last - 1. After this operation the elements in the moved-from range will still contain valid values of the appropriate type, but not necessarily the same values as before the move.

因为该算法在迭代器上运行,所以它实际上无法从 vector 中删除元素。它们仍然存在,并且可以具有与以前相同的值(但不一定)。

此外,字符串仍然存在于 vector 中。从 std::string move 后,它处于有效但未指定的状态。在这种情况下,字符串为空。

关于C++ move () : what's left in the vector?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61484286/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com