The two vectors the user enters will always be in alphabetical order, and the function merge_items
places those values in one vector seeing which one comes before the other by using the < operator, the code initially gave a segmentation fault and at certain times, it doesn't show the last element.
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void merge_items(vector<string>& a1,vector<string>& b1,vector<string>& merged);
int main(){
vector<string> v1,v2;
string a,b;
int n1,n2;
cout << "How many values for v1? " << endl;
cin >> n1;
for(int i = 0;i < n1;i++){
cin >> a;
v1.push_back(a);
}
cout << "How many values for v2? " << endl;
cin >> n2;
for(int i = 0;i < n2;i++){
cin >> b;
v2.push_back(b);
}
vector<string> merge;
merge_items(v1, v2, merge);
for(int i = 0;i < merge.size();i++){
cout << merge[i] << endl;
}
return 0;
}
void merge_items(vector<string>& a1,vector<string>& b1,vector<string>& merged){ int i1 = 0,i2 = 0;
string temp;
while(i1+i2 < (a1.size()-1+b1.size()-1)){
if(a1[i1] < b1[i2]){
temp = a1[i1];
merged.push_back(temp);
i1++;
}else{
temp = b1[i2];
merged.push_back(temp);
i2++;
}
}
}