Skip to content

Instantly share code, notes, and snippets.

@GenesisFR
Last active April 24, 2021 12:56
Show Gist options
  • Save GenesisFR/25b28571ebd4e3ceaa906a92284c7dcd to your computer and use it in GitHub Desktop.
Save GenesisFR/25b28571ebd4e3ceaa906a92284c7dcd to your computer and use it in GitHub Desktop.
#define _IN_FILE "in.txt"
#define _OUT_FILE "out.txt"
#include <fstream>
#include <string>
#include <vector>
#include <algorithm>
#include <windows.h>
using namespace std;
// Source: https://stackoverflow.com/a/20429543
const wstring accentedChars = L"ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ";
const wstring unaccentedChars = L"AAAAAAECEEEEIIIIDNOOOOOx0UUUUYPsaaaaaaeceeeeiiiiOnooooo/0uuuuypy";
// Source: http://www.nubaria.com/en/blog/?p=289
string convertFromUtf16ToUtf8(const wstring& wstr)
{
string convertedString;
int requiredSize = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, 0, 0, 0, 0);
if (requiredSize > 0)
{
vector<char> buffer(requiredSize);
WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), -1, &buffer[0], requiredSize, 0, 0);
convertedString.assign(buffer.begin(), buffer.end() - 1);
}
return convertedString;
}
wstring convertFromUtf8ToUtf16(const string& str)
{
wstring convertedString;
int requiredSize = MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, 0, 0);
if (requiredSize > 0)
{
vector<wchar_t> buffer(requiredSize);
MultiByteToWideChar(CP_UTF8, 0, str.c_str(), -1, &buffer[0], requiredSize);
convertedString.assign(buffer.begin(), buffer.end() - 1);
}
return convertedString;
}
void convertAccents(wstring& str)
{
for (wchar_t& c : str)
{
auto index = accentedChars.find(c);
// Map the accented character to its unaccented equivalent
if (index != wstring::npos)
c = unaccentedChars[index];
}
}
bool sortFunc(const string& strA, const string& strB)
{
// Convert to wide strings
wstring tempStrA = convertFromUtf8ToUtf16(strA);
wstring tempStrB = convertFromUtf8ToUtf16(strB);
// Strip accented characters
convertAccents(tempStrA);
convertAccents(tempStrB);
// Lowercase
transform(tempStrA.begin(), tempStrA.end(), tempStrA.begin(), ::tolower);
transform(tempStrB.begin(), tempStrB.end(), tempStrB.begin(), ::tolower);
return (tempStrA < tempStrB);
}
int main()
{
vector<string> vectEntries;
// Open I/O files
ifstream inFile(_IN_FILE, ifstream::in);
ofstream outFile(_OUT_FILE, ifstream::out);
if (inFile.good())
{
string line;
// Read the entries from the input file
while (getline(inFile, line))
vectEntries.push_back(line);
// Sort them
sort(vectEntries.begin(), vectEntries.end(), sortFunc);
// Write them to the output file
if (outFile.good())
{
for (const string& line : vectEntries)
outFile << line + "\n";
return 0;
}
}
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment