which is most efficient when using std::vector?

aortizb's Avatar, Join Date: Sep 2008
Go4Expert Member
Hello, both codes below do exactly the same and both are working. Here is my question for those more experienced. Which of the two codes below would be the most efficient when working with large vectors?

Code 1:
Code:
#include <iostream>
#include <vector>
using namespace std;

void foo(vector<double>& temp, int length);

int main()
{
	int size = 10000;
	int i;

	vector<double> vec;
	vec.reserve(size);
	
	foo(vec, size);

	for (i = 0; i < size; i++)
		cout << "vec[" << i << "] =" << vec[i] << endl;
	cout << endl;
	
	return 0;
}

void foo(vector<double>& temp, int length)
{
	int i;
	
	for (i = 0; i < length; i++)
		temp.push_back((i + 1) * (i + 1));
}
code 2:
Code:
#include <iostream>
#include <vector>
using namespace std;

vector<double> foo(int length);

int main()
{
	int size = 10000;
	int i;
	
	vector<double> vec = foo(size);
	
	for (i = 0; i < size; i++)
		cout << "vec[" << i << "] =" << vec[i] << endl;
	cout << endl;
	
	return 0;
}

vector<double> foo(int length)
{
	int i;
	
	vector<double> temp;
	temp.reserve(length);
	
	for (i = 0; i < length; i++)
		temp.push_back((i + 1) * (i + 1));
	
	return temp;
}
Is there any other way to do the same that is yet more efficient?

Thanks.
0
aortizb's Avatar, Join Date: Sep 2008
Go4Expert Member
Actually, I found the answer. So no reply is needed.