I'm trying to obtain the sorted position of a string in a list that may contain duplicates.
I don't care about an undefined order for duplicates but I would like a global sort.
Here is my best attempt so far:
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
void display(const std::vector<int> &array)
{
for (const auto & value : array)
std::cout << value << " ";
std::cout << std::endl;
}
std::vector<int> sortIndexes(const std::vector<std::string> &values)
{
std::vector<int> indexes(values.size());
std::iota(indexes.begin(), indexes.end(), 0);
std::stable_sort(indexes.begin(), indexes.end(), [&values](const size_t first, const size_t second)
{
return values.at(first) <= values.at(second);
});
return indexes;
}
int main (void)
{
display(sortIndexes({"b", "a", "c"})); // Expecting: 1 0 2 Result: 1 0 2
display(sortIndexes({"c", "c", "a"})); // Expecting: 1 2 0 or 2 1 0 Result: 2 1 0
display(sortIndexes({"c", "a", "c"})); // Expecting: 1 0 2 or 2 0 1 Result: 1 2 0
return 0;
}
Is there another way to get the expected output ?
EDIT:
I was missing the strict comparison + 'inverseIndexes' part to solve my problem. Here is the updated code:
#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>
void display(const std::vector<int> & array)
{
for (const auto & value : array)
std::cout << value << " ";
std::cout << std::endl;
}
std::vector<int> inverseIndexes(const std::vector<int> & indexes)
{
std::vector<int> inverse(indexes.size());
for (size_t i = 0; i < indexes.size(); ++i)
inverse[indexes[i]] = i;
return inverse;
}
std::vector<int> sortIndexes(const std::vector<std::string> & values)
{
std::vector<int> indexes(values.size());
std::iota(indexes.begin(), indexes.end(), 0);
std::stable_sort(indexes.begin(), indexes.end(), [&values](const size_t first, const size_t second)
{
return values.at(first) < values.at(second);
});
return indexes;
}
int main (void)
{
display(inverseIndexes(sortIndexes({"b", "a", "c"})));
display(inverseIndexes(sortIndexes({"c", "c", "a"})));
display(inverseIndexes(sortIndexes({"c", "a", "c"})));
return 0;
}