Consider the code snippet below:
void PrintLines(vector<string>& lines){}
vector<string> lines = {"Images", "Transcriptions"};
PrintLines(lines);
Is there a possibility to pass the lines values directly, without initializing the "lines" variable?
Like this:
PrintLines({"Images", "Transcriptions"});
CodePudding user response:
First things first, you've not specified the return type of the function when defining it.
Is there a possibility to pass the lines values directly, without initializing the "lines" variable?
Yes, you can do that by making the parameter lines
to be a const lvalue reference to std::vector
so that it can bind to rvalue as shown below:
// vvvvv added low level const here
void PrintLines(const std::vector<std::string>& lines)
^^^^ // added void as return type here
{
for(const std::string&elem: lines)
{
std::cout<<elem<<std::endl;
}
}
int main()
{
PrintLines({"Images", "Transcriptions"});//calls PrintLines
return 0;
}