converting list of strings representing numbers to set
-
i have a list of numbers, i need to join the numbers into a string by
_character.
e.g.QStringList lstStrings{"1", "2", "3"}; std::cout << QStringList(lstStrings.toSet().toList()).join('_').toStdString();this prints
3_1_2. why does this happen?
i expect1_2_3to be printed. -
Please take some time to read the documentation:
QSet is unordered, so an iterator's sequence cannot be assumed to be predictable. If ordering by key is required, use a QMap.
You can try
lstStrings.removeDuplicates(); lstStrings.sort();But still, this
sortwill only sort them as strings, not numbers. -
i have a list of numbers, i need to join the numbers into a string by
_character.
e.g.QStringList lstStrings{"1", "2", "3"}; std::cout << QStringList(lstStrings.toSet().toList()).join('_').toStdString();this prints
3_1_2. why does this happen?
i expect1_2_3to be printed.@user4592357 said in converting list of strings representing numbers to set:
this prints 3_1_2. why does this happen?
Because you went
toSet().i expect 1_2_3 to be printed.
All you needed for this is
QStringList::join(). There is no sorting here.std::cout << lstStrings.join("_"); -
@user4592357 said in converting list of strings representing numbers to set:
this prints 3_1_2. why does this happen?
Because you went
toSet().i expect 1_2_3 to be printed.
All you needed for this is
QStringList::join(). There is no sorting here.std::cout << lstStrings.join("_");@JonB
the reason i usedtoSet()is that the items in my string list may be reordered, and i want to always get the same sequence from same items.
i guess not sorting is fine as long as i get the same result for same input. -
Hi,
You can use QCollator with the numerical mode activated for your numeric text sorting.