使用Vector对子字符串进行降序排序,但存在分割错误

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

本文关键字:排序 存在 错误 分割 降序 Vector 字符串 使用      更新时间:2023-10-16

我想将字符串从N排序到M,其中N表示开始索引,M表示结束索引。

然而,我的代码是失败的分割错误。下面是我的代码:

#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;
}

这个例子对我来说很好:

#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

我怀疑你用cin得到一个空字符串,因此你的data.begin()是无效的。小心用户输入的数据。总是对可能破坏代码的输入进行适当的检查。

另外,您的模板greater是错误类型的比较函数。

以上问题的答案来自Trevir的指导。为了避免分割故障,请检查输入的大小字符串,然后对其应用操作。

#include <iostream>
#include <algorithm>
#include <vector>  
#include <string>
using namespace std;
int main()
{   
    string s;
    int M,N;
    cout<<"Enter String"<<endl;
    getline(cin,s);
    if ( s.size() == 0 )
    {
       std::cout << "Empty Input" << std::endl;   
       return 0;
    }
    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;
}