c++ - 创建字符指针 vector 以指向字符串 vector

标签 c++ string vector chars

我有一个字符串 vector :vectorElements 我想创建一个 *char vector 来指向每个字符串的开头。我的目标是能够逐个字符地遍历每个字符串。最终,我想对字符串 vector 进行排序。 注意:字符串可能包含整数值。在这种情况下,我将根据它们的数值进行排序。

最佳答案

如果你用 C++ 编写,最好使用 C++ string 而不是 char 的 C 样式数组.您仍然可以通过使用 begin() 获取迭代器来遍历每个字符并使用重载运算符 ++在遍历到下一个字符的迭代器上(检查 end() 返回的迭代器以了解您是否到达字符串的末尾)。您还可以使用重载运算符 [] 以 C 风格引用字符串中的字符。 .

因此,一个 vector<string>可能是您需要的。

要对字符串进行排序,您可能需要使用 sort algorithm 中发挥作用 header 。由于您并非始终按词法对它们进行排序,因此您必须定义自己的函数来比较 2 个字符串。

用于比较的

伪代码:

while (i < str1.length() && i < str2.length())
  if (!isDigit(str1[i]) || !isDigit(str2[i]))
    // Lexical comparison
    if (str1[i] != str2[i])
      i++
    else
      return str1[i] < str2[i]
  else // If both are digits
    // parseInt will parse the number starting from current position
    // as positive integer
    // - It will consume as many characters as possible (greedily) and
    // return the parsed number plus the number of characters consumed
    // - If the number is very large (exceed 64-bit), you may want to 
    // only find the length of the number and write another
    // comparison function for big numbers.
    // The code below assumes no overflow
    (num1, len1) = parseInt(str1, i)
    (num2, len2) = parseInt(str2, i)
    if (num1 == num2)
      i += len1
    else
      return num1 < num2

if (str1.length() == str2.length())
  return false
else
  return str1.length() < str2.length()

关于c++ - 创建字符指针 vector 以指向字符串 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10973507/

相关文章:

python - 删除字符串的前 X 个单词和分隔符 - 具有多个分隔符

java - 按位运算检查字符串是否唯一

c++ - 使用 int vector 元素作为输入的递归方法类

c++ - STL 从 vector 中删除与谓词匹配的第一个元素

c++ - 有没有办法禁用临时绑定(bind)到 const 引用?

c++ - 类定义的语法错误

c++ - 创建一个单词移位器

r - 计算 r 中单词向量中特定字母的出现

vector - 有效保留一系列vec元素

c++ - Go 和 C++ 中的 vector 性能