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