Initial commit for WordsSorting
This commit is contained in:
43
WordsSorting/WordProcessing.cpp
Normal file
43
WordsSorting/WordProcessing.cpp
Normal file
@@ -0,0 +1,43 @@
|
||||
#include "WordProcessing.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
|
||||
// Comparator struct for alphabetical sorting
|
||||
// TODO support non ASCII characters in a graceful manner (accents, other alphabets, etc)
|
||||
struct AlphbeticalStringOrdering
|
||||
{
|
||||
bool operator()(string iLeft, string iRight) const
|
||||
{
|
||||
|
||||
string lowerLeft = iLeft, lowerRight = iRight;
|
||||
transform(lowerLeft.begin(), lowerLeft.end(), lowerLeft.begin(), ::tolower);
|
||||
transform(lowerRight.begin(), lowerRight.end(), lowerRight.begin(), ::tolower);
|
||||
|
||||
/* If the strings are the same in case a case insensitive comparisonthen we can keep the default/basic
|
||||
* because we will only compare the case of the letters
|
||||
* If they are different in case insensitive we use this as our basis
|
||||
* because we do not want to risk having a string starting with a 'Z' before a word starting with an 'a'
|
||||
*/
|
||||
bool leftSmaller = iLeft < iRight;
|
||||
if (lowerLeft != lowerRight)
|
||||
{
|
||||
leftSmaller = lowerLeft < lowerRight;
|
||||
}
|
||||
|
||||
return leftSmaller;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
void WordProcessing::ProcessWords(bool isUnique, vector<string>& ioWords)
|
||||
{
|
||||
std::function<bool(string, string)> sorter = AlphbeticalStringOrdering();
|
||||
sort(ioWords.begin(), ioWords.end(), sorter);
|
||||
|
||||
if (isUnique)
|
||||
{
|
||||
auto eraseIt = unique(ioWords.begin(), ioWords.end());
|
||||
ioWords.erase(eraseIt, ioWords.end());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user