1. We have moved from vBulletin to XenForo and you are viewing the site in the middle of the move. Though the functional aspect of everything is working fine, we are still working on other changes including the new design on Xenforo.
    Dismiss Notice

which is most efficient when using std::vector?

Discussion in 'C++' started by aortizb, Sep 28, 2008.

  1. aortizb

    aortizb New Member

    Joined:
    Sep 12, 2008
    Messages:
    32
    Likes Received:
    0
    Trophy Points:
    0
    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.
     
  2. aortizb

    aortizb New Member

    Joined:
    Sep 12, 2008
    Messages:
    32
    Likes Received:
    0
    Trophy Points:
    0
    Actually, I found the answer. So no reply is needed.
     

Share This Page