I have a function that receives an std::vector<int>
as such:
void foo(std::vector<int>);
And I would like to repeatedly call foo()
with small vectors generated on the fly. I was trying to create a new vector on the fly using an initializer list but it seems to allocate a vector of size n, instead of initializing it.
For example:
foo(std::vector<int> { 1});
foo(std::vector<int> { 4});
foo(std::vector<int> { 5});
It seems to create 3 vectors, allocated for 1, 4 and 5 default (0) elements respectively.
Instead I would like to create 3 vectors of size 1, but with value 1, 4 and 5. I am aware I could use the constructor (n, value) like vector<int>
(1,1), (1,4) and (1,5), but for my understanding I would like to understand why my initializer list is not doing what I expect it to.
Declaration std::vector<int> { 1}
creates 1 element with value as 1. Element created will have value 1 at 0th position.
Declaration std::vector<int> (1,6)
creates 1 element with value as 6. Element created will have value 6 at 0th position.
The declaration provided in question work fine.
#include <iostream>
#include <vector>
void foo(std::vector<int> vec)
{
std::cout<<"size of vec "<<vec.size()<<std::endl;
for(int x =0; x < vec.size(); ++x)
{
std::cout<<vec[x]<<std::endl;
}
std::cout<<std::endl;
}
int main()
{
foo(std::vector<int> { 1});
foo(std::vector<int> { 4});
foo(std::vector<int> { 5});
foo(std::vector<int> (1,6));
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With