Kalatxori
Kalatxori

Reputation: 55

How can I merge two vectors?

I'm developing an application and I want to be more efficient. In one important part I have 2 large vectors (with the same size) and I merge one in another. All I want to do is this:

std::vector<int> first (4,2); //A vector containing 4 ints with value 2
std::vector<int> second (4,3);  //A vector with 4 ints with value 3

for(int i = first.size()-1; i > 0; --i){

  first[i] += second[i];

}

How can I do more efficiently? Thanks in advance!

Upvotes: 1

Views: 716

Answers (4)

humble_aspirant
humble_aspirant

Reputation: 11

Try this:

int main()
{
    int first[] = {5,10,15,20,25};
    int second[] = {50,40,30,20,10};
    int len=first.size();
    for(int i = 0; i < second.size(); i++,len++)
    {
        first[len]= second[i];
    }
}

Upvotes: 0

Gluttton
Gluttton

Reputation: 5958

For efficient merge several vectors you should use SIMD (if your hardware support it). There are several ways to do it:

Upvotes: 2

Galik
Galik

Reputation: 48605

You may find this method faster:

int main()
{
    int first = {5, 10, 15, 20, 25};
    int second = {50, 40, 30, 20, 10};

    int* f = first;
    int* e = first + (sizeof(first)/sizeof(int));
    int* s = second;

    while(f != e)
        *f++ += *s++;

    for(std::size_t i = 0; i < sizeof(first)/sizeof(int); ++i)
        std::cout << " " << first[i];
}

Upvotes: 0

FunkyCat
FunkyCat

Reputation: 448

You can use multithread, for example. But your arrays should be really big to get profit - starting from about 1,000,000 elements

Upvotes: 0

Related Questions