vendredi 11 mai 2018

how to merge 2 sorted vectors without standart alorithms?

here is code,it should merge 2 sorted vector and make third sorted vector. when one of the vectors are empty code doesnot work, i think first two if statements have some problems . but it works for filled vectors, any ideas whats the problem?

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void merge(vector<int>&v1, vector<int>&v2, vector<int>&v3) {
while (v1.size()!=0 && v2.size()!=0)
{
    if (v1.empty())
    {
        for (int i = 0; i < v2.size(); i++)
        {
            v3.push_back(v2[i]);
        }
        return;
    }

    if (v2.empty())
    {
        for (int i = 0; i < v1.size(); i++) {
            v3.push_back(v1[i]);
        }
        return;
    }

    if (v1[0] < v2[0])
    {
        v3.push_back(v1[0]);
        v1.erase(v1.begin());
    }
    else
    {
        v3.push_back(v2[0]);
        v2.erase(v2.begin());
    }
}
}
int main() 
{

vector<int> vec1;
vector<int> vec2{ 2,4,6,8,10,24,548,5454 };
vector<int>vec3;
merge(vec1, vec2, vec3);
for (auto v : vec3) cout << v << " ";
cout << "\n";
}

Aucun commentaire:

Enregistrer un commentaire