将数组转换为向量的最简单方法是什么? [英] What is the simplest way to convert array to vector?

查看:34
本文介绍了将数组转换为向量的最简单方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

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

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆