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

所以我有一个问题,涉及在 leetcode 上返回 2 个值作为向量。我想做的是在找到这两个值后,用这些值创建一个新的向量并同时返回该向量。本质上,把线

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

成一行,希望像

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

有可能在 C++ 中做这样的事情吗?

回答

更简洁地说,您可以使用列表初始化。

  1. 在使用花括号初始化列表作为返回表达式和列表初始化初始化返回对象的返回语句中
std::vector<int> foo(int a, int b)
{
    return {a, b};
}

  • Note: C++ has [a lot of initialization options](https://en.cppreference.com/w/cpp/language/initialization). It's in your best interests to be familiar with them so you can pick and chose the best one for a given job. Sometimes the options get, well, [nightmarish](https://www.youtube.com/watch?v=7DTlWPgX6zs).

以上是是否可以在C++中初始化一个向量并同时返回它?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>