c++ - vector 的 std::copy 无法正常工作

标签 c++ algorithm vector stl copy

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<int> a{ 1, 2, 3 };
    copy(a.begin(), a.end(), back_inserter(a));
    for (const int& x : a)
        cout << x << ' ';
}
输出:
1 2 3 1 -572662307 -572662307
预期输出:
1 2 3 1 2 3
我不知道为什么会这样。这种行为的原因是什么?

最佳答案

问题在于,随着 vector 的增长,您提供的迭代器可能会失效。您可以使用 reserve 解决此问题.一般来说,最好使用 reserve如果您提前知道大小,那么分配会减少:

#include <algorithm>
#include <vector>

int main() {
  std::vector<int> a{1, 2, 3};
  a.reserve(a.size() * 2);

  a.insert(a.end(), a.begin(), a.end());
}
请注意 insert通常比 back_inserter 更好、更简单.

关于c++ - vector 的 std::copy 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67943471/

相关文章:

java - ™ 字符未被 GetStringChars() 正确翻译

algorithm - 对 "two-sum"有 O(n^2) 算法,转换为 O(n) 线性解

Ruby - 使用哈希返回数组中的重复项,这有效吗?

java - 从外部元素到内部元素遍历数组

c++ - 与size_t比较,返回int?

c++ - 无法在 C++ 中创建结构 vector

C++ 对象或二维数组作为参数?

c++ - 并行命令模式

c++ - iterator::operator* 的标准接口(interface)返回的内容多于 T& 和 std::pair

C++如何将 map 复制到 vector