mercredi 10 novembre 2021

c++ pass newly created vector as parameter

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?

Aucun commentaire:

Enregistrer un commentaire