How do I pass multiple ints into a vector at once?

后端 未结 6 1998
北荒
北荒 2020-12-01 04:08

Currently when I have to use vector.push_back() multiple times.

The code I\'m currently using is

  std::vector TestVector;
         


        
6条回答
  •  臣服心动
    2020-12-01 04:44

    You can also use vector::insert.

    std::vector v;
    int a[5] = {2, 5, 8, 11, 14};
    
    v.insert(v.end(), a, a+5);
    

    Edit:

    Of course, in real-world programming you should use:

    v.insert(v.end(), a, a+(sizeof(a)/sizeof(a[0])));  // C++03
    v.insert(v.end(), std::begin(a), std::end(a));     // C++11
    

提交回复
热议问题