什么是转换阵列向量最简单的方法? [英] What is the simplest way to convert array to vector?
本文介绍了什么是转换阵列向量最简单的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
什么是数组转换为载体的最简单方法?
What is the simplest way to convert array to vector?
void test(vector<int> _array)
{
...
}
int x[3]={1, 2, 3};
test(x); // Syntax error.
我要X的int数组转换成最简单的方法载体。
I want to convert x from int array to vector in simplest way.
推荐答案
使用矢量
构造函数,两个迭代器,请注意指针是有效的迭代器,并使用了含蓄从数组转换为指针:
Use the vector
constructor that takes two iterators, note that pointers are valid iterators, and use the implicit conversion from arrays to pointers:
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]));
其中, sizeof的X / sizeof的X [0]
显然是 3
在这种情况下,它是得到在阵列元素的数量的通用方法。需要注意的是 X + sizeof的X / sizeof的X [0]
指向一个元素的超过的最后一个元素。
where sizeof x / sizeof x[0]
is obviously 3
in this context; it's the generic way of getting the number of elements in an array. Note that x + sizeof x / sizeof x[0]
points one element beyond the last element.
这篇关于什么是转换阵列向量最简单的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文