Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

inserting into vectors c++

Tags:

c++

c++11

vector

I need to push 66,000 vectors (the number of vectors is not fixed, it can be 90,000 vectors also. For the sake of brevity I am showing the below code with the example of 66,000 vectors) of type vector into the following vector:

vector<int> vec;

The size of each of the 66,000 vectors is 9,000 elements. I am using the following for doing the same:

vec.reserve(66000*9000);
for(int j=0;j<66000;j++)
    for(int i=0;i<9000;i++) //9000 elements in vec1[i] per vector is not fixed
        vec.push_back(vec1[i]); //i am pushing i as an example

Is there someway by which I may increase the efficiency of this code?

I need to concatenate too many vectors, so a solution for the same is potentially different from concatenating two vectors. Also I can not use multi-threading as mentioned in the previous question

like image 340
Steg Verner Avatar asked Mar 16 '23 10:03

Steg Verner


2 Answers

Try the following

std::vector<int> vec;
vec.reserve( 66000*other_vec.size() );

for ( size_t i = 0; i < 66000; i++ ) 
{
    vec.insert( vec.end(), other_vec.begin(), other_vec.end() );
}
like image 192
Vlad from Moscow Avatar answered Mar 19 '23 19:03

Vlad from Moscow


You may use resize() instead of reserve(). Remove push_back when resize() is used. Memory is allocated with resize() and initializes. reserve just allocates but doesn't initialize.

like image 29
Satish Chalasani Avatar answered Mar 19 '23 18:03

Satish Chalasani