开发者

Initializing multiple (unique) entries of a vector

With an array you can do this:

int a[] = { 1,2,3,4,5,6 }

How do you do 开发者_高级运维this with a vector?


You could write this, though its not an initialization, but looks very appealing:

std::vector<int> v;
v << 1,2,3,4,5,6,7,8,9,10; //all pushed into the vector!

And to support this syntax, you need two utility operators defined as:

template<typename T>
std::vector<T>& operator << (std::vector<T>& v, const T & item)
{
    v.push_back(item);  return v;
}
template<typename T>
std::vector<T>& operator,(std::vector<T>& v, const T & item)
{
    v.push_back(item);  return v;
}

And you're done!

Test code:

int main() {
       std::vector<int> v;
       v << 1,2,3,4,5,6,7,8,9,10;

       for ( size_t i = 0 ; i < v.size() ; ++i )
             std::cout << v[i] << " ";
}

Output:

1 2 3 4 5 6 7 8 9 10 

Online demo : http://www.ideone.com/1hyR3

Using the utility operators, you actually can avoid temporary variables such as the one in @Als's solution, and you can write this without boost!


If you are using Boost, You can simply use Boost.Assign

std::vector<int> v = boost::assign::list_of(1)(2)(3)(4)(5)(6);

Or

If you are not using Boost, you can do it in two steps:

static const int a[] = {1,2,3,4,5,6};
vector<int> v (a, a + sizeof(a) / sizeof(a[0]) );


If you don't want to use boost, you can use this:

std::vector<int> myvec;
int myints[] = {1776, 7, 4};
myvec.assign(myints, myints + 3);

Not exactly the same, but it comes very close. I always use this.


As of C++ 11 you can create a vector object with list-initialization as follows:

std::vector<int> v1 = {1, 2, 3, 4};
std::vector<int> v2 {1, 2, 3, 4};

And in C++ 17 you can omit the type to allow C++ to infer the type based on the datatype passed in the list (provided you don't mix the types):

// C++ 17
std::vector v3 = {1, 2, 3, 4};
std::vector v4 {1, 2, 3, 4};
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜