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

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

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

我知道的最好的方法是:

std::vector<int> ints;

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

有没有更好的办法?


当前回答

c++ 11:

static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));

其他回答

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

#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;
}

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

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

arr a {10, 20, 30};       // This would be how you initialize while defining

编译使用:

clang++ -std=c++11 -stdlib=libc++  <filename.cpp>

如果数组是:

int arr[] = {1, 2, 3};
int len = (sizeof(arr)/sizeof(arr[0])); // finding length of array
vector < int > v;
v.assign(arr, arr+len); // assigning elements from array to vector 

维克多·塞尔(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)