创建字符指针的向量以指向字符串的向量
creating vectors of character pointers to point to vector of strings
我有一个字符串向量:vectorElements我想创建一个 *char 向量来指向每个字符串的开头。我的目标是能够逐个字符遍历每个字符串。最终,我想对字符串的向量进行排序。注意:字符串可能包含整数值。在这种情况下,我将根据它们的数值进行排序。
如果你用C++编写,最好使用C++ string
而不是char
的C样式数组。您仍然可以通过使用 begin()
获取迭代器来遍历每个字符,并在迭代器上使用重载运算符++
遍历到下一个字符(检查 end()
返回的迭代器以了解您是否到达字符串的末尾)。您还可以使用重载运算符 []
引用 C 样式字符串中的字符。
因此,vector<string>
可能是您需要的。
要对字符串进行排序,您可能需要algorithm
标头中使用sort
函数。由于您不是一直按词法对它们进行排序,因此您必须定义自己的函数来比较 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()
您可以使用 std::sort。
for ( int i=0; i<vec.size(); ++i )
{
std::string & str = vec[i];
std::sort(str.begin(), str.end());
}
演示
相关文章:
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- 构造<int>具有 2 个字符串文字的向量
- 如何将元素添加到向量的字符串位置
- 将向量解析<string>为字符串
- C ++中的StringStream有助于使用向量从字符串中提取逗号分隔的整数,而不是空格分隔的整数,为什么?
- 在 C++11 中,如何查找并返回以给定字符串开头的字符串向量中的所有项?
- 如何使用向量字符串令牌构建表达树
- 将 argv 复制到新的全局向量字符串
- 如何读取控制台输入并将其存储到向量字符串中
- 向量字符串push_back在C 中不起作用
- C char数组和向量字符串
- 可以直接初始化向量<字符串 *> 而不使用 new 吗?
- 迭代向量字符串的字符(C++禁止指针和整数之间的比较)
- 比较两个向量字符串的相似性C++
- 我有麻烦将字符串放入向量字符串
- 如何从一个向量字符串得到一个字符串的联合集
- 函数返回向量/字符串,但不返回数组
- 向量向量字符串固定大小
- c++向量字符串排序不工作
- C++将字符串数组[]复制到向量<字符串>