且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

是否可以在 C++ 中初始化一个向量并同时返回它?

更新时间:2023-11-09 23:52:52

更简洁,您可以使用 列表初始化.

  1. 在使用花括号初始化列表作为返回表达式和列表初始化初始化返回对象的返回语句中

std::vectorfoo(int a, int b){返回{a, b};}

So I have a question that involves returning 2 values as a vector on leetcode. What I want to do is after finding these two values, create a new vector with these values and return the vector at the same time. Essentially, turn the lines

vector<int> temp;
temp.push_back(a);
temp.push_back(b);
return temp;

into one line, hopefully something like

return new vector<int>{a,b};

Is it possible to do something like this in C++?

Even more concisely, you can use list initialization.

  1. in a return statement with braced-init-list used as the return expression and list-initialization initializes the returned object

std::vector<int> foo(int a, int b)
{
    return {a, b};
}