[英]creating vectors of character pointers to point to vector of strings
我有一個字符串向量:vectorElements我想創建一個* char的向量來指向每個字符串的開頭。 我的目標是能夠逐個字符地遍歷每個字符串。 最后,我想對字符串向量進行排序。 注意:字符串可能包含整數值。 在這種情況下,我將根據他們的數值進行排序。
如果您使用C ++編寫,最好使用C ++ string
而不是C樣式的char
數組。 您仍然可以通過使用begin()
獲取迭代器來迭代每個字符,並在迭代器上使用重載的operator ++
來遍歷下一個字符(使用end()
返回的迭代器進行檢查,以了解是否到達字符串的末尾或不)。 您還可以使用重載的operator []
引用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());
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.