Farhan Patel Farhan Patel - 2 months ago 5
C++ Question

Sort a Substring in Descending order using Vector, however getting segmentation fault

I want to sort the string from N to M where N indicates the starting index and M indicates the ending index.

However, my code is getting failed with segmentation fault.
Here is my code:

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

using namespace std;

int main()
{
string s;
int M=0,N=0;

cout<<"Enter String"<<endl;
getline(cin,s);

vector<char> data(s.begin(), s.end());

cout<<"Enter start_index and end_index for sorting";
cin>>N>>M; //Passed externally as N=start_index, M=end_index

std::sort(data.begin()+N, data.begin()+M, std::greater<char>());

for (std::vector<char>::const_iterator i = data.begin(); i != data.end(); ++i)
std::cout << *i << ' ';

return 0;
}

Answer

This example does work fine for me:

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

using namespace std;

int main()
{   
    string s = "ABCDEFG";
    int N = 1;
    int M = 5;

    vector<char> data(s.begin(), s.end());

    std::sort(data.begin() + N, data.begin() + M, std::greater<char>());

    for (auto& character : data)
        std::cout << character << ' ';
    return 0;
}

http://coliru.stacked-crooked.com/a/ee7c5f05afe85115

I suspect you get an empty string with cin, and therefore your data.begin() is invalid. Be cautious with user entered data. Always do proper checking for input that may break your code.

Additonally your templated greater is the comparing function for the wrong type.

Comments