Go4Expert

Go4Expert (http://www.go4expert.com/)
-   C++ (http://www.go4expert.com/forums/cpp/)
-   -   which is most efficient when using std::vector? (http://www.go4expert.com/forums/efficient-using-stdvector-t14240/)

aortizb 28Sep2008 14:59

which is most efficient when using std::vector?
 
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.

aortizb 29Sep2008 01:22

Re: which is most efficient when using std::vector?
 
Actually, I found the answer. So no reply is needed.


All times are GMT +5.5. The time now is 03:17.