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

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

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

我知道的最好的方法是:

std::vector<int> ints;

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

有没有更好的办法?


当前回答

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

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

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

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) );

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

其他回答

我倾向于宣称

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

在一个实用程序头的某处,然后所需要的是:

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

最简单的,符合人体工学的方法(c++ 11或更高版本):

auto my_ints = {1,2,3};

维克多·塞尔(Viktor Sehr)给出了一个最近的重复问题的答案。对我来说,它很紧凑,在视觉上很吸引人(看起来就像你在“塞”值),不需要c++ 11或第三方模块,并且避免使用额外的(编写的)变量。下面是我如何使用它与一些变化。将来我可能会转而扩展vector和/或va_arg的函数。


// Based on answer by "Viktor Sehr" on Stack Overflow
// https://stackoverflow.com/a/8907356
//
template <typename T>
class mkvec {
    public:
        typedef mkvec<T> my_type;
        my_type& operator<< (const T& val) {
            data_.push_back(val);
            return *this;
        }
        my_type& operator<< (const std::vector<T>& inVector) {
            this->data_.reserve(this->data_.size() + inVector.size());
            this->data_.insert(this->data_.end(), inVector.begin(), inVector.end());
            return *this;
        }
        operator std::vector<T>() const {
            return data_;
        }
    private:
        std::vector<T> data_;
};

std::vector<int32_t> vec1;
std::vector<int32_t> vec2;

vec1 = mkvec<int32_t>() << 5 << 8 << 19 << 79;
// vec1 = (5, 8, 19, 79)
vec2 = mkvec<int32_t>() << 1 << 2 << 3 << vec1 << 10 << 11 << 12;
// vec2 = (1, 2, 3, 5, 8, 19, 79, 10, 11, 12)

如果你的编译器支持可变宏(这对大多数现代编译器都是正确的),那么你可以使用下面的宏把矢量初始化变成一行代码:

#define INIT_VECTOR(type, name, ...) \
static const type name##_a[] = __VA_ARGS__; \
vector<type> name(name##_a, name##_a + sizeof(name##_a) / sizeof(*name##_a))

使用这个宏,你可以用这样的代码定义一个初始化的向量:

INIT_VECTOR(int, my_vector, {1, 2, 3, 4});

这将创建一个名为my_vector的int型新向量,元素为1,2,3,4。

// Before C++11
// I used following methods:

// 1.
int A[] = {10, 20, 30};                              // original array A

unsigned sizeOfA = sizeof(A)/sizeof(A[0]);           // calculate the number of elements

                                                     // declare vector vArrayA,
std::vector<int> vArrayA(sizeOfA);                   // make room for all
                                                     // array A integers
                                                     // and initialize them to 0 

for(unsigned i=0; i<sizeOfA; i++)
    vArrayA[i] = A[i];                               // initialize vector vArrayA


//2.
int B[] = {40, 50, 60, 70};                          // original array B

std::vector<int> vArrayB;                            // declare vector vArrayB
for (unsigned i=0; i<sizeof(B)/sizeof(B[0]); i++)
    vArrayB.push_back(B[i]);                         // initialize vArrayB

//3.
int C[] = {1, 2, 3, 4};                              // original array C

std::vector<int> vArrayC;                            // create an empty vector vArrayC
vArrayC.resize(sizeof(C)/sizeof(C[0]));              // enlarging the number of 
                                                     // contained elements
for (unsigned i=0; i<sizeof(C)/sizeof(C[0]); i++)
     vArrayC.at(i) = C[i];                           // initialize vArrayC


// A Note:
// Above methods will work well for complex arrays
// with structures as its elements.