【问题标题】:Sorting char pointer using STL sort()使用 STL sort() 对字符指针进行排序
【发布时间】:2020-09-11 06:58:48
【问题描述】:

有人知道如何使用std::sort() STL 函数对char* 进行排序吗?在c++中

如果我使用 sort(str.begin(),str.end()); 之类的排序。一个错误来了 - 'request for member begin and end in str, which is non-char type 'char*'.

我知道如何在#include<algorithm> 中使用std::sort() 对字符串进行排序

【问题讨论】:

  • 所有std::sort 需要的是指向第一个元素的“指针”,以及指向最后一个元素之外的元素的“指针”。对于以 null 结尾的字节字符串,很容易获得这两个指针。
  • 如果我使用 sort(str.begin(),str.end()); 之类的排序。一个错误来了——'request for member begin and end in str, which is non-char type 'char*'.
  • 注意我评论中的pointer这个词...

标签: c++ sorting c++11 stl


【解决方案1】:

如果你有一个指向字符串开头的指针,你可以直接把它作为第一个参数传递给std::sort

那么第二个参数需要是指向字符串end的指针。您可以通过向该指针添加字符串长度来获取它。

std::sort(ptr, ptr + std::strlen(ptr));

【讨论】:

  • 你能告诉我如何实现 std::unique() 吗
  • @silkynene 几乎所有算法函数都使用“开始”迭代器和“结束”迭代器处理范围。对于 C 风格的以空字符结尾的字符串,“begin”迭代器是指向第一个字符的指针,“end”迭代器是指向终止符的指针。使用该信息以及此答案中的信息,这告诉您什么?你认为你应该怎么打电话,例如std::unique(期望基本相同的论点)?
  • std::unique(ptr, ptr+std::strlen(ptr));但是如何退货呢?
  • @silkynene 它会返回一个指针,所以char *new_end = std::unique(...);。新的字符串大小为new_end - ptr。您可能还想在新的末尾插入一个空终止符 (*new_end = '\0';)。
  • 如何返回这个值?
【解决方案2】:

你可以对 char* 字符串进行排序,但你不能修改字符串字面量,所以你需要将字符串作为一个 char 数组才能对其进行修改(包括排序):

//this is a string literal that can't be modified
const char* string_literal = "this can't be modified";

// this is a char[] that is initialized from a string literal
char str1[] = { "can modify" };
//array can be converted to pointer to first element
char* str_ptr = str1;
//str1 can be directly passed to sort, i just added str_ptr to make the conversion explicit
std::sort(str_ptr, str_ptr + std::strlen(str_ptr));

//the method with std::begin only works for char[], doesn't work for char*
//this could be initialized with a string literal as in previous example
char str2[] = { 'c', 'a', 'n', ' ', 'm', 'o', 'd', 'i', 'f', 'y', '\0' };

//end -1 because we want to keep the last character in place (the end string null termination character)
std::sort(std::begin(str2), std::end(str2) - 1);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多