I want to insert only few values say 3 integers in a vector.Is there any way other than this
vector<int>v;
v.push_back(a1);
v.push_back(a2);
v.push_back(a3);
Any way other than this.Anything in one line ?
Something like this would work:
int arr[] = { 4, 5, 6, 7 };
std::vector<int> v1 (arr, arr + sizeof(arr) / sizeof(arr[0]));
If you're using C++11, you have more options:
std::vector<int> v2 (std::begin(arr), std::end(arr));
or, even better, without a temporary array:
std::vector<int> v3 { 1, 2, 3 };
if you are aware before hand how much elements are needed to placed in vector, you can std::vector::reserve function. But it will not shrink the initial capacity of the vector.
To make sure the capacity is of low count say 3 in your case, you may need to use C++11 function added, std::vector::shrink_to_fit() function. Here you can pass int parameter in this function to make sure you only reserve elements you want in vector. example usage.
vector<int> vi;
vi.shrink_to_fit(3); // only takes 3 elements.
// now add 3 elements as you need.
hope this helps.