将数组转换为向量的最简单方法是什么

What is the simplest way to convert array to vector?

本文关键字:最简单 方法 是什么 向量 数组 转换      更新时间:2023-10-16

将数组转换为向量的最简单方法是什么?

void test(vector<int> _array)
{
  ...
}
int x[3]={1, 2, 3};
test(x); // Syntax error.

我想用最简单的方法将x从int数组转换为向量。

使用采用两个迭代器的vector构造函数,注意指针是有效的迭代器,并使用从数组到指针的隐式转换:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + sizeof x / sizeof x[0]);
test(v);

test(std::vector<int>(x, x + sizeof x / sizeof x[0]));

其中CCD_ 2在该上下文中显然是CCD_;这是获取数组中元素数量的通用方法。注意,x + sizeof x / sizeof x[0]指向最后一个元素之外的一个元素

就我个人而言,我非常喜欢C++2011方法,因为它既不需要使用sizeof(),也不需要在更改数组边界时记住调整数组边界(如果愿意,也可以在C++2003中定义相关函数):

#include <iterator>
#include <vector>
int x[] = { 1, 2, 3, 4, 5 };
std::vector<int> v(std::begin(x), std::end(x));

显然,对于C++2011,您可能无论如何都希望使用初始值设定项列表:

std::vector<int> v({ 1, 2, 3, 4, 5 });

指针可以像任何其他迭代器一样使用:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + 3);
test(v)

您在这里问了一个错误的问题——与其把所有东西都强制转换成向量,不如问您如何将测试转换为使用迭代器而不是特定容器。为了保持兼容性(同时免费处理其他容器),您也可以提供过载:

void test(const std::vector<int>& in) {
  // Iterate over vector and do whatever
}

变为:

template <typename Iterator>
void test(Iterator begin, const Iterator end) {
    // Iterate over range and do whatever
}
template <typename Container>
void test(const Container& in) {
    test(std::begin(in), std::end(in));
}

让你做什么:

int x[3]={1, 2, 3};
test(x); // Now correct

(Ideone演示)

一种简单的方法是使用vector类中预定义的assign()函数。

例如

array[5]={1,2,3,4,5};
vector<int> v;
v.assign(array, array+5); // 5 is size of array.

一种方法是一次性使用数组的绑定,如下所示:

 int a[3] = {1, 2, 3};
vector<int> v(a, *(&a+1));