是否可以在 C++ 中初始化一个向量并同时返回它? [英] Is it possible to initialize a vector and return it at the same time in c++?

查看:28
本文介绍了是否可以在 C++ 中初始化一个向量并同时返回它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

vector温度;temp.push_back(a);temp.push_back(b);返回温度;

成一行,希望像

返回新向量{a,b};

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

解决方案

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

<块引用>

  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};
}

这篇关于是否可以在 C++ 中初始化一个向量并同时返回它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆