If I have a function that expects a std::pair
or std::array
for example, I can do the following:
#include <array>
#include <string>
void foo(std::array<int,5>){}
void bar(std::pair<int,std::string>){}
int main(){
foo({1,2,3,4,5});
bar(std::make_pair(1, "test"));
}
What would be a similiar way of passing a std::vector
as a parameter?
Is there a way to pass a std::vector
that is beeing created in the same line as the call to a function that expects it as a parameter?
How to achieve the requested with the following:
#include <vector>
#include <string>
void testVector(std::vector<std::string> &t){}
int main(){
std::vector<std::string> boring; // I dont want to create a vector like this
testVector(boring); // this works obviously
testVector({"hello"}); //this does not work
testVector(std::vector<std::string>(){"test"}); // does not work aswell
}
I just edited the question because I wanted to pass a reference. But I think there is no way of passing a reference to a vector that was instantiated that way right?
CodePudding user response:
using
void baz(std::vector<int> vec) { … }
works:
…
baz({1,2,3});
…
But: using a plain vector as signature will lead to every function call making a copy of the vector. You very rarely actually want that, unless your method actually needs a copy for some reason.
The usual way is to use a reference:
void baz_ref(std::vector<int>& vec) { … }
which means that now, the function doesn't get a copy, but works on the original vector – but that means your function might have side effects that the calling function doesn't expect!
Also, you can't call baz_ref({1, 2, 3});
, because that would pass a reference to a temporary object.
In cases where your function doesn't need to modify the vector:
void baz_constref(const std::vector<int>& vec) { … }
is the way to go – no copy, trying to modify vec
won't work. The compiler can beautifully optimize this, and you can also call baz_constref({1, 2, 3});
.
There's another option: Move semantics, and it might be the right thing if your function actually modifies the vector – should that function be the new "owner"? Then, you should move that vector into the function, but the calling function then loses the ability to use it.
CodePudding user response:
Firstly your entry point is wrong, it should be int main
and not void main
. And the following code works
#include <vector>
#include <string>
void testVector(std::vector<std::string>){}
int main()
{
std::vector<std::string> boring;
testVector(boring);
testVector({"hello"}); // This works
testVector(std::vector<std::string>{"test"}); // This works too :)
}