I am trying out the various ways of creating std::vector
on the fly and passing it to another function:
#include <iostream>
#include <vector>
void print(std::vector<int> a)
{
std::cout << a.size() << '\n';
}
int main()
{
print({1, 2, 3, 4, 5});
print(std::vector<int>{1, 2, 3, 4, 5});
print(std::vector<int>({1, 2, 3, 4, 5}));
}
This produces the desired output:
$ clang++ -std=c++11 foo.cpp && ./a.out
5
5
5
I want to know what are the differences between these three invocations:
print({1, 2, 3, 4, 5});
print(std::vector<int>{1, 2, 3, 4, 5});
print(std::vector<int>({1, 2, 3, 4, 5}));
Here is another example:
#include <iostream>
#include <vector>
int main()
{
std::vector<int> a = {1, 2, 3, 4, 5};
// std::cout << (a == {1, 2, 3, 4, 5}) << '\n'; // error
std::cout << (a == std::vector<int>{1, 2, 3, 4, 5}) << '\n';
std::cout << (a == std::vector<int>({1, 2, 3, 4, 5})) << '\n';
}
Here is the output:
$ clang++ -std=c++11 foo.cpp && ./a.out
1
1
I am hoping that the answer to this question can become a good reference answer on this topic where the answer discusses the following aspects of these invocations:
- The above three and any other similar ways of passing a
std::vector
to another function. - Semantic differences between the various methods.
- Performance differences (if any) between the various methods.
- Best practices (if any) due to which one invocation is favourable over another.
If you think the question has any shortcomming, please feel free to edit the question and improve it.