C++ 为什么使用选择排序对字符串进行排序不能正常工作?
这段代码没有给出任何语法错误,但有一些逻辑错误,我无法找到它。 代码是:C++ 为什么使用选择排序对字符串进行排序不能正常工作?,c++,sorting,selection-sort,C++,Sorting,Selection Sort,这段代码没有给出任何语法错误,但有一些逻辑错误,我无法找到它。 代码是: #include<iostream> #include<cstring> void SortString(std::string str, int size) { int min; for(int i = 0; i < size-2; i++) { min = i; for(int j = i+1; j < size-2; j++)
#include<iostream>
#include<cstring>
void SortString(std::string str, int size)
{
int min;
for(int i = 0; i < size-2; i++)
{
min = i;
for(int j = i+1; j < size-2; j++)
{
if( str[j] < str[min] )
min = j;
}
char temp = str[i];
str[i] = str[min];
str[min] = temp;
}
std::cout<<std::endl<<str<<std::endl;
}
int main()
{
std::string str;
std::cout<<"\n Enter a string to sort : ";
std::getline(std::cin, str);
std::cout<<"\n String after sorting is : \n";
SortString(str, strlen(str.c_str()));;
//std::cout<<str<<std::endl;
return 0;
}
二,
同样的逻辑也适用于对整数数组进行排序。但是它对字符串不起作用。需要注意的关键是,如果你看两个例子:
lovely ==>
elovly
program ==>
goprram
它看起来像在做什么?在我看来,它似乎在对最后两个字符进行排序
你的循环边界是什么样子的
for(int i = 0; i < size-2; i++)
{
min = i;
for(int j = i+1; j < size-2; j++)
为什么要数到2号?这样,您就看不到最后两个字符了。首先,声明第二个参数没有什么意义,因为类型为
std::string
的对象将有关其大小的信息保存在其内部
在外环中也存在这种情况
for(int i = 0; i < size-2; i++)
^^^^^^^^^^
仅供参考,您可以使用
std::sort
对字符串进行排序:std::sort(str.begin(),str.end())代码>
for(int i = 0; i < size-2; i++)
{
min = i;
for(int j = i+1; j < size-2; j++)
void SortString(std::string& str)
{
int min;
for(int i = 0; i < str.size(); i++)
{
min = i;
for(int j = i+1; j < str.size(); j++)
{
if( str[j] < str[min] )
min = j;
}
std::swap(str[i], str[min]);
}
}
for(int i = 0; i < size-2; i++)
^^^^^^^^^^
void SortString( std::string str )
{
for ( std::string::size_type i = 0; i < str.size(); i++ )
{
std::string::size_type min = i;
for ( std::string::size_type j = i + 1; j < str.size(); j++ )
{
if ( str[j] < str[min] ) min = j;
}
if ( i != min ) std::swap( str[i], str[min] );
}
std::cout << std::endl << str << std::endl;
}