简体   繁体   English

创建字符指针的向量以指向字符串的向量

[英]creating vectors of character pointers to point to vector of strings

I have a vector of strings: vectorElements I'd like to create a vector of *char to point to the beginning of each string. 我有一个字符串向量:vectorElements我想创建一个* char的向量来指向每个字符串的开头。 My objective is to be able to traverse through each string, character by character. 我的目标是能够逐个字符地遍历每个字符串。 Ultimately, I'd like to sort the vector of strings. 最后,我想对字符串向量进行排序。 Note: Strings may contain integer values. 注意:字符串可能包含整数值。 In which case, I'll be sorting based on their numeric value. 在这种情况下,我将根据他们的数值进行排序。

If you are writing in C++, it is better to use C++ string instead of the C style array of char . 如果您使用C ++编写,最好使用C ++ string而不是C样式的char数组。 You can still iterate through each character with by obtaining the iterator with begin() and use overloaded operator ++ on the iterator to traverse to next character (check with iterator returned by end() to know whether you reached the end of the string or not). 您仍然可以通过使用begin()获取迭代器来迭代每个字符,并在迭代器上使用重载的operator ++来遍历下一个字符(使用end()返回的迭代器进行检查,以了解是否到达字符串的末尾或不)。 You can also refer to character in the string in C style with overloaded operator [] . 您还可以使用重载的operator []引用C风格的字符串中的字符。

Therefore, a vector<string> may be what you need. 因此, vector<string>可能就是您所需要的。

To sort the strings, you may want to use sort function in algorithm header. 要对字符串进行排序,您可能希望在algorithm标题中使用sort函数。 Since you are not sorting them lexically all the time, you have to define your own function that compares between 2 strings. 由于您不是一直在词法上对它们进行排序,因此您必须定义自己的函数来比较2个字符串。

Pseudocode for the comparison: 用于比较的伪代码

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()

You can use std::sort . 你可以使用std :: sort

for ( int i=0; i<vec.size(); ++i )
{
    std::string & str = vec[i];
    std::sort(str.begin(), str.end());
}

Demo 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM