使用Vector对子字符串进行降序排序,但存在分割错误
Sort a Substring in Descending order using Vector, however getting segmentation fault
我想将字符串从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;
}
相关文章:
- C++模板来检查友元函数的存在
- 二叉排序树无法编译
- 既然存在危险,为什么项目要使用-I include开关
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 我们可以访问一个不存在的联盟的成员吗
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- C++为什么我的指针选择排序中存在分段错误?
- 这种排序算法已经存在吗?
- 是否有用于排序和查找 c++ 中是否已存在的值的函数?
- 我的选择排序代码是否存在导致它跳过数组中的元素的问题?
- 是否存在用于按以下方式对两个范围进行排序和分区的标准算法?
- Bool排序的插入函数,检查列表中是否已经存在int
- 为什么这两个版本的快速排序在进行比较的次数上存在巨大差异
- 插入时对对象进行排序(若存在,则添加数据)
- "std::"具有排序/排序、存在测试和头/尾访问的数据结构?
- 是否存在按主键和从键排序的容器
- 对于未排序的范围,是否存在std::includes等价项
- 使用Vector对子字符串进行降序排序,但存在分割错误
- 是否存在任何键值容器来存储它们的元素而不进行任何重新排序?