1

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!



// 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; 
}


Justin
  • 177
  • 8
  • Please provide a [mre] anf explain what makes you think that something is wrong. – Yunnosch Jan 09 '22 at 14:20
  • 2
    It looks like you expect `std::vector vec1{5};` to be size 5. You should double check that. – cigien Jan 09 '22 at 14:21
  • Hey! Thanks for the feedback! As I mentioned in the description the compiler prints 0 in the terminal when I run this code! – Justin Jan 09 '22 at 14:21

2 Answers2

2

The brackets you use to initialize your vectors are wrong, should be (), not {}. See here for 6 methods of initializing the vectors in C++.

Yulia V
  • 3,507
  • 10
  • 31
  • 64
1

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 = {...}.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207