What is this way that something weird return?

I was solving Leetcode, and I saw someone's code.
and I saw an interesting code that when a function returns vector<int>, It returns like this way.

1
2
3
4
vector<int> retVec()
{
	return { 1, 3, 5 };
}


and It's really working.
I think it's more efficient and simple and faster than a normal way.
you guys think It's really do? or Not?


1
2
3
4
5
6
7
8
9
// a normal way
vector<int> retVec()
{
	vector<int> tmp;
	tmp.push_back(1);
	tmp.push_back(3);
	tmp.push_back(5);
	return tmp;
}
Last edited on
It calls the constructor which take an initializer list. See:

http://www.cplusplus.com/reference/vector/vector/vector/

It's C++11 the constructor (6).
In other words it is closer to:
1
2
3
4
5
6
// a normal way
vector<int> retVec()
{
	vector<int> tmp { 1, 3, 5 };
	return tmp;
}

If you start empty and do push_back, then you most likely invoke reallocations within the vector (unless the compiler miraculously is able to optimize them away). You could avoid those with:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// a normal way
vector<int> retVec()
{
	vector<int> tmp;
	tmp.reserve( 3 );
	tmp.push_back(1);
	tmp.push_back(3);
	tmp.push_back(5);
	return tmp;
}

// or
vector<int> retVec()
{
	vector<int> tmp( 3 );
	tmp[0] = 1;
	tmp[1] = 3;
	tmp[2] = 5;
	return tmp;
}
Last edited on
return { 1, 3, 5 };

where are you going to get those values. What you most definitely do NOT want to do is:
1
2
3
4
5
6
7
8
vector<int> retVec()
{
	vector<int> tmp;
	tmp.push_back(1);
	tmp.push_back(3);
	tmp.push_back(5);
	return {tmp[0], tmp[1], tmp[2] };  // Look how smart I am!
}


This is actually slower than
1
2
3
4
5
6
7
8
9
// a normal way
vector<int> retVec()
{
	vector<int> tmp;
	tmp.push_back(1);
	tmp.push_back(3);
	tmp.push_back(5);
	return tmp;
}

This is because of "copy elision" (did I spell that right?). The compiler will recognize that tmp is the return vector and will store it in the return value. So when you return, it doesn't have to make a copy at all.

But this is like optimizing a ventilation system by examining how much air is moved by flies. It's a tiny gain and probably not worth any consideration.
Thank you, guys!!
Topic archived. No new replies allowed.