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

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

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

我知道的最好的方法是:

std::vector<int> ints;

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

有没有更好的办法?


当前回答

如果数组是:

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)

在c++ 0x中,你可以用与数组相同的方式来做这件事,但不是在当前的标准中。

只有语言支持,您可以使用:

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

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

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

要避免硬编码数组的大小:

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

如果数组是:

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 

在编写测试时,创建一个内联的向量而不定义变量是非常方便的,例如:

assert(MyFunction() == std::vector<int>{1, 3, 4}); // <- this.

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

#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。