简体   繁体   English

使用Vector按降序对子字符串进行排序,但是出现分段错误

[英]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. 我想对字符串从N到M进行排序,其中N表示开始索引,M表示结束索引。

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

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 http://coliru.stacked-crooked.com/a/ee7c5f05afe85115

I suspect you get an empty string with cin, and therefore your data.begin() is invalid. 我怀疑您使用cin获得了一个空字符串,因此您的data.begin()无效。 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. 此外,模板化的更大是错误类型的比较功能。

The answer to the above question is from the guidance of Trevir. 上述问题的答案来自Trevir的指导。 In order to avoid the segmentation fault, check the size of the input string and then apply operations on it. 为了避免分段错误,请检查输入字符串的大小,然后对其进行操作。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM