which is most efficient when using std::vector?

Go4Expert Member
28Sep2008,14:59   #1
aortizb's Avatar
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.
Go4Expert Member
29Sep2008,01:22   #2
aortizb's Avatar
Actually, I found the answer. So no reply is needed.