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

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

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

我知道的最好的方法是:

std::vector<int> ints;

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

有没有更好的办法?


当前回答

“我如何创建一个STL向量并像上面那样初始化它?用最少的打字工作量做到这一点的最佳方法是什么?”

在初始化内置数组时,初始化vector最简单的方法是使用c++ 11中引入的初始化列表。

// Initializing a vector that holds 2 elements of type int.
Initializing:
std::vector<int> ivec = {10, 20};


// The push_back function is more of a form of assignment with the exception of course
//that it doesn't obliterate the value of the object it's being called on.
Assigning
ivec.push_back(30);

执行赋值(标签语句)后,ivec大小为3个元素。

其他回答

一种方法是使用数组初始化vector

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

c++ 11:

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

使用Boost list_of:

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

使用Boost赋值:

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

传统的STL:

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

带有通用宏的常规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));

带有矢量初始化宏的常规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);

这里有很多很好的答案,但由于我在阅读这篇文章之前独立地得到了我自己的答案,我想无论如何我都要在这里抛出我的答案……

下面是我使用的一个方法,它将在编译器和平台上普遍工作:

创建一个结构体或类作为对象集合的容器。为<<定义运算符重载函数。

class MyObject;

struct MyObjectList
{
    std::list<MyObject> objects;
    MyObjectList& operator<<( const MyObject o )
    { 
        objects.push_back( o );
        return *this; 
    }
};

你可以创建以你的结构体作为参数的函数,例如:

someFunc( MyObjectList &objects );

然后,你可以调用这个函数,像这样:

someFunc( MyObjectList() << MyObject(1) <<  MyObject(2) <<  MyObject(3) );

这样,您就可以在一行代码中构建并将动态大小的对象集合传递给函数!

开始:

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

如果你没有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

如果你没有c++ 11编译器,可以使用Boost:

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

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

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

如果你想把它放在你自己的课上:

#include <initializer_list>
Vector<Type>::Vector(std::initializer_list<Type> init_list) : _size(init_list.size()),
_capacity(_size),
_data(new Type[_size])
{
    int idx = 0;
    for (auto it = init_list.begin(); it != init_list.end(); ++it)
        _data[idx++] = *it;
}