Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

Is it possible to initialize a vector and return it at the same time in c++?

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++?

question from:https://stackoverflow.com/questions/66055843/is-it-possible-to-initialize-a-vector-and-return-it-at-the-same-time-in-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...