函数sort
必须对字符串中的字母进行排序。但是没有使用内置的 C++sort()
函数!我尝试了不同的方法,但没有任何帮助。这是此函数中的参数。需要排序text
。(是否可以在不删除&
之前进行此操作text
?)此代码进入无限循环。
std::string TextUtility::sort(const std::string &text)
{
string toSort = text;
string sorted_str;
int size = sizeof(toSort) / sizeof(char);
for (int i = 0; i < size - 1; i++)
{
if (toSort[i] > toSort[i + 1])
{
int temp = toSort[i + 1];
toSort[i + 1] = toSort[i];
toSort[i] = temp;
i = -1;
}
}
for (int i = 0; i < toSort.size(); i++)
{
sorted_str += toSort[i];
}
cout << endl
<< "Sorted: " << sorted_str;
return sorted_str;
}
清理后(见评论)这似乎工作得很好。
#include <string>
#include <iostream>
std::string sort(const std::string &text)
{
std::string toSort = text;
for (int i = 0; i < (int)(toSort.size()) - 1; i++)
{
if (toSort.at(i) > toSort.at(i + 1))
{
char temp = toSort.at(i + 1);
toSort.at(i + 1) = toSort.at(i);
toSort.at(i) = temp;
i = -1;
}
}
std::cout << "Sorted: " << toSort << std::endl;
return toSort;
}
int main()
{
sort("fgfghafbkgdbGHKGHjbkgfnvnbjb14563f");
sort("X");
sort("");
return(0);
}
已排序:13456GGHHKabbbbbdfffffgggghjjkknnv
排序:X
排序:
顺便说一句:需要显式转换 (int)(toSort.size()),因为空字符串会破坏条件。至少在我的系统上,它会导致“i < size_t(-1)”,从而导致 std::out_of_range。也许类似的事情导致了你的无限循环?
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句