关于函数返回值是vector({}/大括号)的一些理解

57 篇文章 9 订阅

最近看到有人用函数返回了一个大括号感到不解,查了一下,如下。

下面是原文:


问:Returning constructor arguments in braces?

I am new to C++ and the brace initialization (or uniform init) really is confusing. What exactly happens when a function returns a list of arguments in braces? Thanks a lot for claryfying.

std::vector<double> foo()
{
  return {1, 2}; // is this the same as: std::vector<double>{1, 2} or std::vector<double>(1, 2)? or something else?
}

答:

return {1, 2};, the return value is list-initialized from {1, 2}, as the effect, the returned std::vector<double> contains 2 elements with value 1 and 2.

看了这个之后还是有点不懂,直到知道了vector的初始化方式感觉有点理解了

问:Initializing vector with double curly braces

Code:

vector<string> v = {"a", "b"};
string c(v[0] + v[1]);
cout << "c = " << c;

Output:

c = ab

答:

vector<string> v = {"a", "b"}; You initialize the vector by providing an initializer list with two elements. The two std::strings are initialized from the string literals, and then copied into the vector.

这里其实是给出了一个初始化方式:vector<string> v = {"a", "b"};


所以我做了一个实验来给vector初始化:

#include<iostream>
#include<string>
#include<vector>
using namespace std;
int main() {
	vector<string> v = { "a", "b" };
	string c(v[0] + v[1]);
	cout << "c = " << c << endl;
	cout << "---------------------------" << endl;
	vector<int> v1 = { 1,2 };
	cout << v1[0] << " " << v1[1] << endl;
	cout << "---------------------------" << endl;
	vector<double> v2 = { 1,1.0,2.37 };//可以vector<double>赋值int类型
	cout << v2[0] << " " << v2[1] << " " << v2[2] << endl;
	cout << "---------------------------" << endl;
	//vector<int> v3 = { 1,2.1 };//会报错,不行,不能给vector<int>赋值double类型
	return 0;
}

在这里插入图片描述
所以也就理解了这个函数为什么可以这样写了:

std::vector<double> foo() return {1, 2};

这个函数可以返回一个{1,2},因为会给接收的vector初始化赋值

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值