如何在C ++中对同时包含负数和正数的字符串数组进行排序?

Emp*_*mp1 7 c++ arrays sorting string algorithm

String str[]={"-123","89","-10","456"};
Run Code Online (Sandbox Code Playgroud)

str是一个字符串数组,每个字符串都是整数格式,您必须及时对该数组进行排序O(n log n)

中的字符串str可以表示正整数和负整数。这些字符串的最大长度为1024个字符。

我知道解决此问题的一种方法是将字符串转换为数字,然后将它们进行比较。还有其他解决方案吗?

use*_*109 12

另一个解决方案是实现自己的比较功能:

  • 检查两个字符串的第一个字符。如果一个以数字开头,另一个以开头,则以开头-的字符串- 是较小的数字。
  • 如果两个字符串都以数字开头,则比较字符串的长度。字符串越短,数字越小。如果两个字符串长度相同,请执行标准字符串比较。
  • 如果两个字符串都以开头-,则比较字符串的长度。字符串越长,数字越小。如果两个字符串的长度相同,请执行标准字符串比较,但取反结果。

  • 这很容易补救。使用find_first_not_of(“ 0”)中的索引,并将其传递给compare()重载,该重载要求pos / len作为比较的两面。 (3认同)

dru*_*nly 11

这是一个最小且可能不足(无法处理前导零,空白等)的示例,可以满足您的要求。

这些评论说明了它在做什么。:)

#include <algorithm>
#include <iostream>
#include <string>
#include <vector>

int main() {
  std::vector<std::string> strings = {
      "-1", "-1", "-20", "-4", "3", "0", "-0", "1", "20", "20", "44020",
  };

  // Assumes everything in "strings" has no whitespace in it.
  // Assumes everything in "strings" does not have leading zeroes.
  // Assumes everything in "strings" is an ascii representaion of an integer.
  // Assumes everything in "strings" is nonempty.
  std::sort(strings.begin(), strings.end(),
            [](const std::string &a, const std::string &b) {
              const bool a_is_negative = a[0] == '-';
              const bool b_is_negative = b[0] == '-';
              if (a_is_negative != b_is_negative) {
                // If they have different signs, then whichever is negative is
                // smaller.
                return a_is_negative;
              } else if (a.length() != b.length()) {
                // If they have the same sign, then whichever has more
                // characters is larger in magnitude. When the sign is negative,
                // the longer (more digits) number is "more negative". When
                // positive, the longer (more digits) number is "more positive".
                return (a.length() < b.length()) != a_is_negative;
              } else {
                // Otherwise a lexicographic comparison of "a" and "b" will
                // determine which string is larger in magnitude. Using the same
                // logic above, we account for the "negative vs. positive"
                // comparison.
                return (a < b) != a_is_negative;
              }
            });

  for (const auto &str : strings) {
    std::cout << str << " ";
  }
  std::cout << std::endl;
}
Run Code Online (Sandbox Code Playgroud)