将数组转换为向量的最简单方法是什么
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数组转换为向量。
使用采用两个迭代器的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));
相关文章:
- 当无法使用模板和宏时,生成类型变体C++代码的最简单方法是什么?
- 在OSX上使用CMake将Adobe的XMP工具包构建为共享库的最简单方法是什么?
- 通过比较C++中的行在 txt 文件中搜索的最简单方法是什么?
- 将时间戳打印到流的最简单方法
- 在C++中创建文件夹选取器对话框的最简单方法是什么?
- boost::variant - 对变体应用算术的最简单方法
- 创建可以遍历 std::map 值的通用模板迭代器的最简单方法是什么?
- 在C++中将算术类型转换为 std::array 的最简单方法<uint8_t>
- C++-将ASCII字符数组中可能的数值转换为字符的最简单方法
- 从 txt 文件中读取数据的最简单方法
- 根据浮点符号对浮点进行舍入的最简单方法是什么
- 对于我扩展此程序来计算最高10x10矩阵的倒数的最简单方法是什么
- C++98 中获取并继续调用当前类不知道的类方法的最简单方法是什么?
- 编写要在 Python 中使用的并行 C/C++ 模块的最简单方法
- 开放式颜色多边形表面的最简单方法
- 确定代码中当前程序集是否为 32/64 位的最简单方法
- 将unique_ptr存储在堆上的最简单方法是什么
- 使用 C# 获取 OpenGL 版本的最简单方法
- 在自定义 C/C++ 程序中获取 PPP0 接口 Tx/Rx 字节的最简单方法是什么?
- 为depth_first_search定义颜色图的最简单方法