c++ - 将 int 数组的内容写入 vector

标签 c++ stl vector

我想将数组的内容写入 vector 。

int A[]={10,20,30,40,50,60,70,80,90};
vector<int> my_vector;

之前,我曾使用 memcpy 将数组 A 的内容复制到另一个数组 B 中。我想使用 my_vector 而不是数组 B

如何在没有 for 循环的情况下一次性将数组 A 的内容写入 my_vector?

最佳答案

用你想用的C++ 2011

std::copy(std::begin(A), std::end(A), std::back_inserter(my_vector));

...或者

std::vector<int> my_vector(std::begin(A), std::end(A));

...或者,实际上:

std::vector<int> my_vector({ 10, 20, 30, 40, 50, 60, 70, 80, 90 });

如果你没有C++ 2011,你想定义

namespace whatever {
    template <typename T, int Size>
    T* begin(T (&array)[Size]) { return array; }
    template <typename T, int Size>
    T* end(T (&array)[Size]) { return array + Size; }
}

并使用 whatever::begin()whatever::end() 以及前两种方法之一。

关于c++ - 将 int 数组的内容写入 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12242546/

相关文章:

c++ - 使用 scons,如何链接到预建库?

C++ STL算法(列表排序)OpenMP/多线程实现

c++ - 在 public const 方法中访问私有(private)成员

c++ - 在 C++ 中初始化静态 std::map<int, int>

c++ - 从 vector 数组调用函数

c++ - 错误 : type 'std::__1::basic_string<char>' does not provide a call operator

c++ - 如何强制线程严格按顺序工作?

c++ - 我的程序在结束后卡住

c++ - 如何维护对 std::priority_queue 容器的引用?

c++ - 访问顺序序列元素的通用方法