creating vectors of character pointers to point to vector of strings
Domanda
I have a vector of strings: vectorElements I'd like to create a vector of *char to point to the beginning of each string. 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.
Soluzione
If you are writing in C++, it is better to use C++ string
instead of the C style array of 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). You can also refer to character in the string in C style with overloaded operator []
.
Therefore, a vector<string>
may be what you need.
To sort the strings, you may want to use sort
function in algorithm
header. Since you are not sorting them lexically all the time, you have to define your own function that compares between 2 strings.
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()