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

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

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

我知道的最好的方法是:

std::vector<int> ints;

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

有没有更好的办法?


当前回答

如果你不想使用Boost,但想享受语法

std::vector<int> v;
v+=1,2,3,4,5;

只需要包含这段代码

template <class T> class vector_inserter{
public:
    std::vector<T>& v;
    vector_inserter(std::vector<T>& v):v(v){}
    vector_inserter& operator,(const T& val){v.push_back(val);return *this;}
};
template <class T> vector_inserter<T> operator+=(std::vector<T>& v,const T& x){
    return vector_inserter<T>(v),x;
}

其他回答

如果你想要一个与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);

“我如何创建一个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个元素。

有各种方法来硬编码一个向量。我将分享一些方法:

通过逐个推入值来初始化 //创建一个空向量 向量< int > vect; vect.push_back (10); vect.push_back (20); vect.push_back (30); 初始化类似数组 Vector <int> Vector {10,20,30}; 从数组初始化 Int arr[] = {10,20,30}; Int n = sizeof(arr) / sizeof(arr[0]); Vector <int> Vector (arr, arr + n); 从另一个向量初始化 Vector <int> vect1{10,20,30}; Vector <int> Vector (Vector 1.begin(), Vector 1.end()));

c++ 11:

static const int a[] = {10, 20, 30};
vector<int> vec (begin(a), end(a));
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>