Home > Software engineering >  How do I return specific vector elements in c elegantly
How do I return specific vector elements in c elegantly

Time:01-31

I am working on a problem in which I must return a type vector. I know the size of the vector will be exactly two. Is there a way I can return my values in vector form without creating a new vector variable and returning that?

I've tried the following method, but it did not work. As well as curly braces and straight braces.

vector<int> foo()
{
    return <1,2>;
}

CodePudding user response:

If you use C 11 or higher version, Just write:

vector<int> foo()
{
    return {1,2};
}

{1, 2} will be deduced as an initializer_list, and it won't cause a copy since we have 'Copy elision'. Since it doesn't have a name, which is also called 'Return Value Optimization'.

You can see in: https://en.cppreference.com/w/cpp/language/copy_elision https://en.cppreference.com/w/cpp/utility/initializer_list

CodePudding user response:

Is there a way I can return my values in vector form without creating a new vector variable and returning that?

You are already returning by value which by definition involves a copy. If you want to avoid the copying you could try returning by reference.


Now, with C 11 and onwards we should replace the angle brackets <> by braces {} as shown below:

//vvvvvvvvvvv------------------>You're returning by value!
  vector<int> foo()
  {
//---------vvvvv------------->changed <> to {}
    return {1,2};
  }
  • Related