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.
Asked
Active
Viewed 222 times
0
-
Can you write in C++? Or must you write in C code? – nhahtdh Jun 11 '12 at 00:44
-
It's a little unclear to me what your question actually is. Could you post an example of code that you have, perhaps with commented stubs for the parts that you don't know how to create? – Nate Kohl Jun 11 '12 at 01:21
2 Answers
2
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()

nhahtdh
- 55,989
- 15
- 126
- 162
0
You can use std::sort.
for ( int i=0; i<vec.size(); ++i )
{
std::string & str = vec[i];
std::sort(str.begin(), str.end());
}

Mahesh
- 34,573
- 20
- 89
- 115
-
You'll need to include a custom comparator to meet the OPs desire to treat strings that "contain a numerical value" differently than the default lexigraphical sort. – dmckee --- ex-moderator kitten Jun 11 '12 at 04:40