通过交换指针对字符数组进行排序,C++
Sorting char arrays by swapping pointers, C++
我正在尝试通过交换指针对字符指针数组(char * _string)进行排序。
我有这个方法,我想做的是使用我从_string获得的值,并通过不操作_string而是操作空的帮助程序数组(char * _output)来对它们进行排序,我也将其交给该方法。
谁能帮助我,告诉我我做错了什么?
void sortAsc(char* _string, char* _output)
{
int length = strlen(_string);
// output and string now point to the same area in the memory
_output = _string;
for( int i = 0; i < length; i++) {
for( int j = 0; j < length; j++) {
if( *(_output) > (_output[j] ) ) {
// save the pointer
char* tmp = _output;
// now output points to the smaller value
_output = _output+j;
// move up the pointer to the smaller value
_output + j;
// now the pointer of the smaller value points to the higher value
_output = tmp;
// move down to where we were + 1
_output - j + 1;
}
}
}
//_output[length]=' ';
//delete chars;
}
在我的主方法中,我做了这样的事情:
char * string = {"bcdae"};
char * output = new char[5];
sortAsc(string, output);
在该代码之后,我希望输出数组包含排序的值。
让我们使用指针符号对 10 大小的 int 数组进行选择排序,您可以简单地将其更改为数组列表。
*---*---*---*---*---* ........
a[] = | 1 | 2 | 4 | 0 | 3 | ........
*---*---*---*---*---* ........
^--------We start here looking for the smaller numbers and sort the array.
for( i = 0; i < 10; i++ ){
k = i;
bypass = *( a + i );
for( j = i + 1; j < 10; j++ ){
/* To get Increasing order. */
if( bypass > *( a + j ) ){
bypass = *( a + j );
k = j;
}
}
if ( k != i ){
*( a + k ) = *( a + i );
*( a + i ) = bypass;
}
}
这会将字符串排序到已分配的缓冲区中,如果缓冲区不够大,则告诉您它必须有多大:
std::size_t sortAsc(char const* string, char* dest, std::size_t dest_length) {
std::size_t str_length = strlen(string);
char const* str_end = string + str_length;
if (dest_length < str_length+1)
return str_length+1;
std::copy( string, str_end, output );
output[str_length] = ' ';
std::sort( output, output+strlen(output) );
return str_length+1;
}
这使用上面的实现来做糟糕的"分配新字符串"模式:
char* allocate_and_sortAsc(char const* string) {
std::size_t str_length = strlen(string);
char* retval = new char[str_length+1];
std::size_t count = sortAsc( string, retval, str_length+1);
ASSERT( count <= str_length );
return retval;
}
并且不要使用以_
开头的变量名称,这是一种不好的做法,因为它非常靠近编译器保留名称。 _Capital
到处都是保留的,_lower
在全球范围内,foo__bar
无处不在。
相关文章:
- 二叉排序树无法编译
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- C++选择排序算法中的逻辑错误
- 使用C++程序合并排序没有得到正确的输出
- 计算排序向量的向量中唯一值的计数
- 排序算法c++
- 使用2个键的cpp-stl::优先级队列排序不正确
- 将结构向量排序为子组
- 在c++中尝试对对象数组进行排序时,出现std:bad_alloc错误
- 如何对点云数据进行排序
- 对字符串进行排序时,在c++中处理sort()
- 是否有类似std::lower_bound的函数,而不需要排序/分区输入
- 下面是排序算法O(n)吗
- std::sort()函数无法对向量的一部分进行排序
- shell排序中的交换和比较
- clang格式:禁用排序包含
- 显示错误输出的简单数组排序程序
- 为什么我的排序算法会更改数组值
- 试图在c++中对数字列表进行排序
- 如何在C++中对数组进行冒泡排序