Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is my simple merge algorithm c++ not working?

I’m trying to merge two sorted vectors into a third one. However, the compiler gives me 0 in the terminal!!

Can someone please tell me what I’m doing wrong?

Thanks!

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel



// merging two sorted vectors

std::vector<int> vec1{5};
std::vector<int> vec2{5};
std::vector<int> vec3{10};

for(int i = 0; i < 5; i++){
 vec1[i] =  2 * i;
}

for(int i = 0; i < 5 ; i++){
 vec2[i] = 2 + 2 * i;
}

std::sort(vec1.begin(), vec1.end());
std::sort(vec2.begin(), vec2.end());

std::merge(vec1.begin(), vec1.end(), vec2.begin(), vec2.end(), vec3.begin());

for(auto itr = vec3.begin(); itr != vec3.end(); ++itr){
    std::cout << " " << *itr; 
}


>Solution :

All your vectors have .size() == 1, so you’re going out of bounds, and the behavior is undefined.

Use () instead of {}:

std::vector<int> vec1(5);
std::vector<int> vec2(5);
std::vector<int> vec3(10);

You should never use the {...} syntax with containers (as opposed to = {...} or {}), because it has a rather peculiar behavior.

If the elements were not ints (and not constructible from ints), it would’ve worked as you expect:

std::vector<int> x(3); // size=3, [0,0,0]
std::vector<int> x{3}; // size=1, [1]
std::vector<int> x = {3}; // size=1, [1]

struct A {};
std::vector<A> x(3); // size=3, [A{}, A{}, A{}]
std::vector<A> x{3}; // size=3, [A{}, A{}, A{}]
std::vector<A> x = {3}; // compilation error
std::vector<A> x = {A{}}; // size=1, [A{}]

Notice that the behavior of {...} changes depending on the element type, but that doesn’t happen with (...) or = {...}.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading