Afr0
Afr0

Reputation: 41

Arranging elements from two vectors alphabetically into one vector

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++;

    }
}
}

Upvotes: 1

Views: 303

Answers (1)

Benjamin Lindley
Benjamin Lindley

Reputation: 103733

This is the appropriate way to merge:

std::merge(a1.begin(), a1.end(),
           b1.begin(), b1.end(),
           std::back_inserter(merged));

As far as what's wrong with your solution. A couple things.

First, once you reach the end of one of the two vectors, you need to stop comparing against that vector and just copy whatever elements are left from the other vector. So you need to compare i1 against a1.size(), separately from your comparison of i2 against b1.size(). With what you're doing now, when you reach the end of one vector, you continue comparing against out of bounds elements from that vector, which is undefined behavior, and likely the cause of your segmentation faults.

Second, you don't need to be subtracting 1 from the size of the vectors. The way you're doing it will leave you with a merged vector which has 2 fewer elements than the combined sizes of the source vectors.

Upvotes: 2

Related Questions