Home > OS >  Why it shows illegal memory location when sorting vector after merge?
Why it shows illegal memory location when sorting vector after merge?

Time:12-02

I tried to sort a new vector after merge two vector, the code like that,

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>

using namespace std;

void vec_output(vector <int> vec_input)
{
    
    for (int i = 0; i < vec_input.size(); i  )
    {
        cout << vec_input[i] << ' ';
    }
    cout << endl;
}

int main(){
    vector <int> v1{2,3,1};
    vector <int> v2{5,4,6};
    vector <int> v3;
    set_union(v1.begin(), v1.end(), v2.begin(), v2.end(), v3.begin());
    sort(v3.begin(), v3.end());
    vec_output(v3);
    return 0;
}

However, it shows error:Exception has occurred. Segmentation fault, I know it may cause by accessing unknown memory,but how?

CodePudding user response:

The problem is that v3 is empty so writing v.begin() as the last argument to set_union isn't possible. You should use back_inserter as:

set_union(v1.begin(), v1.end(), v2.begin(), v2.end(),  std::back_inserter(v3));

The std::back_inserter will return an output iterator back_insert_iterator that will use v3.push_back to append/push_back elements into v3.

Also, from std::set_union documentation:

Elements are compared using operator< and the ranges must be sorted with respect to the same.

(Emphasis mine)

Note also that after using set_union you don't need to use std::sort on v3.

  • Related