Suppose I have code such as the following, to sort elements of a data structure in another data structure, but keep a record of their original indices:
std::vector<int> numbers = {..};
std::vector<std::pair<int, std::vector<int>::size_type>> temp;
for (std::vector<int>::size_type i = 0; i < numbers.size(); i++)
{
temp.push_back({ numbers[i], i });
}
std::sort(temp.begin(), temp.end(), [](const auto& x, const auto& y) { return x.first < y.first; });
So far so good. But what I really want is to store the data and indices in different data structures:
std::vector<int> sorted;
std::vector<std::vector<int>::size_type> indices;
Such that the element at sorted[i]
was at index indices[i]
in the original data structure.
Other than rolling out my own sorting algorithm, or splitting the data structure after the fact, is there any easy trick using the standard library to do this?