C++ 用硬编码元素初始化 std::vector 的最简单方法是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2236197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 22:39:39  来源:igfitidea点击:

What is the easiest way to initialize a std::vector with hardcoded elements?

c++vectorstlinitialization

提问by Agnel Kurian

I can create an array and initialize it like this:

我可以创建一个数组并像这样初始化它:

int a[] = {10, 20, 30};

How do I create a std::vectorand initialize it similarly elegant?

我如何创建一个std::vector并初始化它同样优雅?

The best way I know is:

我所知道的最好的方法是:

std::vector<int> ints;

ints.push_back(10);
ints.push_back(20);
ints.push_back(30);

Is there a better way?

有没有更好的办法?

采纳答案by Yacoby

One method would be to use the array to initialize the vector

一种方法是使用数组来初始化向量

static const int arr[] = {16,2,77,29};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

回答by Manuel

If your compiler supports C++11, you can simply do:

如果您的编译器支持 C++11,您可以简单地执行以下操作:

std::vector<int> v = {1, 2, 3, 4};

This is available in GCC as of version 4.4. Unfortunately, VC++ 2010 seems to be lagging behind in this respect.

从版本 4.4 开始,这在 GCC 中可用。不幸的是,VC++ 2010 在这方面似乎落后了。

Alternatively, the Boost.Assignlibrary uses non-macro magic to allow the following:

或者,Boost.Assign库使用非宏魔法来实现以下功能:

#include <boost/assign/list_of.hpp>
...
std::vector<int> v = boost::assign::list_of(1)(2)(3)(4);

Or:

或者:

#include <boost/assign/std/vector.hpp>
using namespace boost::assign;
...
std::vector<int> v;
v += 1, 2, 3, 4;

But keep in mind that this has some overhead (basically, list_ofconstructs a std::dequeunder the hood) so for performance-critical code you'd be better off doing as Yacoby says.

但请记住,这有一些开销(基本上,在幕后list_of构造一个std::deque),因此对于性能关键的代码,您最好按照 Yacoby 所说的去做。

回答by Adam Erickson

If you can, use the modern C++[11,14,17,...] way:

如果可以,请使用现代 C++[11,14,17,...] 方式:

std::vector<int> vec = {10,20,30};

The old way of looping over a variable-length array or using sizeof()is truly terrible on the eyes and completely unnecessary in terms of mental overhead. Yuck.

循环可变长度数组或使用的旧方法sizeof()在眼睛上确实很糟糕,并且在精神开销方面完全没有必要。哎呀。

回答by David Rodríguez - dribeas

In C++0x you will be able to do it in the same way that you did with an array, but not in the current standard.

在 C++0x 中,您将能够以与使用数组相同的方式执行此操作,但在当前标准中则不然。

With only language support you can use:

仅使用语言支持,您可以使用:

int tmp[] = { 10, 20, 30 };
std::vector<int>?v(?tmp,?tmp+3?);?//?use?some?utility?to?avoid hardcoding the size here

If you can add other libraries you could try boost::assignment:

如果您可以添加其他库,您可以尝试 boost::assignment:

vector<int> v = list_of(10)(20)(30);

To avoid hardcoding the size of an array:

为了避免对数组的大小进行硬编码:

// option 1, typesafe, not a compile time constant
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
   return N;
}
// option 2, not typesafe, compile time constant
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))

// option 3, typesafe, compile time constant
template <typename T, std::size_t N>
char (&sizeof_array( T(&)[N] ))[N];    // declared, undefined
#define ARRAY_SIZE(x) sizeof(sizeof_array(x))

回答by mbells

In C++11:

在 C++11 中:

#include <vector>
using std::vector;
...
vector<int> vec1 { 10, 20, 30 };
// or
vector<int> vec2 = { 10, 20, 30 };

Using boost list_of:

使用 boost list_of:

#include <vector>
#include <boost/assign/list_of.hpp>
using std::vector;
...
vector<int> vec = boost::assign::list_of(10)(20)(30);

Using boost assign:

使用提升分配:

#include <vector>
#include <boost/assign/std/vector.hpp>
using std::vector;
...
vector<int> vec;
vec += 10, 20, 30;

Conventional STL:

常规 STL:

#include <vector>
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, arr + sizeof(arr) / sizeof(arr[0]) );

Conventional STL with generic macros:

具有通用宏的常规 STL:

#include <vector>
#define ARRAY_SIZE(ar) (sizeof(ar) / sizeof(ar[0])
#define ARRAY_END(ar) (ar + ARRAY_SIZE(ar))
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec (arr, ARRAY_END(arr));

Conventional STL with a vector initializer macro:

带有向量初始值设定项宏的常规 STL:

#include <vector>
#define INIT_FROM_ARRAY(ar) (ar, ar + sizeof(ar) / sizeof(ar[0])
using std::vector;
...
static const int arr[] = {10,20,30};
vector<int> vec INIT_FROM_ARRAY(arr);

回答by M. Tibbits

Just thought I'd toss in my $0.02. I tend to declare this:

只是想我会扔掉我的 0.02 美元。我倾向于声明:

template< typename T, size_t N >
std::vector<T> makeVector( const T (&data)[N] )
{
    return std::vector<T>(data, data+N);
}

in a utility header somewhere and then all that's required is:

在某处的实用程序标题中,然后所需要的是:

const double values[] = { 2.0, 1.0, 42.0, -7 };
std::vector<double> array = makeVector(values);

But I can't wait for C++0x. I'm stuck because my code must also compile in Visual Studio. Boo.

但我等不及 C++0x。我被卡住了,因为我的代码也必须在 Visual Studio 中编译。嘘。

回答by A J

Before C++ 11 :

在 C++ 11 之前:

Method 1=>

方法 1=>

vector<int> v(arr, arr + sizeof(arr)/sizeof(arr[0]));
vector<int>v;

Method 2 =>

方法 2 =>

 v.push_back(SomeValue);

C++ 11 onward below is also possible

下面的 C++ 11 也是可能的

vector<int>v = {1, 3, 5, 7};

回答by Carl

Starting with:

从...开始:

int a[] = {10, 20, 30}; //i'm assuming a is just a placeholder

If you don't have a C++11 compiler and you don't want to use boost:

如果您没有 C++11 编译器并且不想使用 boost:

const int a[] = {10, 20, 30};
const std::vector<int> ints(a,a+sizeof(a)/sizeof(int)); //make it const if you can

If you don't have a C++11 compiler and can use boost:

如果您没有 C++11 编译器并且可以使用 boost:

#include <boost/assign.hpp>
const std::vector<int> ints = boost::assign::list_of(10)(20)(30);

If you do have a C++11 compiler:

如果你有 C++11 编译器:

const std::vector<int> ints = {10,20,30};

回答by Tush_08

For vector initialisation -

对于向量初始化 -

vector<int> v = {10,20,30}

can be done if you have c++11 compiler.

如果您有 c++11 编译器,则可以完成。

Else, you can have an array of the data and then use a for loop.

否则,您可以拥有一个数据数组,然后使用 for 循环。

int array[] = {10,20,30}
for(unsigned int i=0; i<sizeof(array)/sizeof(array[0]); i++)
{
     v.push_back(array[i]);
}

Apart from these, there are various other ways described above using some code. In my opinion, these ways are easy to remember and quick to write.

除此之外,还有使用一些代码在上面描述的各种其他方法。在我看来,这些方式很容易记住,写起来也很快。

回答by Paul Baltescu

The easiest way to do it is:

最简单的方法是:

vector<int> ints = {10, 20, 30};