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

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或更高版本):

auto my_ints = {1,2,3};

其他回答

c++ 11:

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

如果可以,使用现代c++[11,14,17,20,…]):

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

在变长数组上循环或使用sizeof()的旧方法真的很糟糕,而且在精神开销方面完全没有必要。讨厌的东西。

你可以使用boost::assign:

vector<int> values;
values += 1,2,3,4,5,6,7,8,9;

详情在这里。

我使用va_arg构建自己的解决方案。该解决方案是c++ 98兼容的。

#include <cstdarg>
#include <iostream>
#include <vector>

template <typename T>
std::vector<T> initVector (int len, ...)
{
  std::vector<T> v;
  va_list vl;
  va_start(vl, len);
  for (int i = 0; i < len; ++i)
    v.push_back(va_arg(vl, T));
  va_end(vl);
  return v;
}

int main ()
{
  std::vector<int> v = initVector<int> (7,702,422,631,834,892,104,772);
  for (std::vector<int>::const_iterator it = v.begin() ; it != v.end(); ++it)
    std::cout << *it << std::endl;
  return 0;
}

Demo

如果你想要一个与Boost::assign相同的顺序,而不需要创建对Boost的依赖关系,那么下面的代码至少大致类似:

template<class T>
class make_vector {
    std::vector<T> data;
public:
    make_vector(T const &val) { 
        data.push_back(val);
    }

    make_vector<T> &operator,(T const &t) {
        data.push_back(t);
        return *this;
    }

    operator std::vector<T>() { return data; }
};

template<class T> 
make_vector<T> makeVect(T const &t) { 
    return make_vector<T>(t);
}

虽然我希望使用它的语法更简洁,但它仍然不是特别糟糕:

std::vector<int> x = (makeVect(1), 2, 3, 4);