The best example I\'ve got is that I want to sort Names based on their Score.
vector Names {\"Karl\", \"Martin\", \"Paul\", \"Jennie\"};
vecto
As already suggested in other answers: Combining the name and the score of each individual is likely the simplest solution.
Generically, this can be achieved with what is sometimes referred to as a "zip" operation: Combining two vectors into a vector of pairs - along with a corresponding "unzip".
Implemented generically, this may look as follows:
#include
#include
#include
#include
#include
// Fill the zipped vector with pairs consisting of the
// corresponding elements of a and b. (This assumes
// that the vectors have equal length)
template
void zip(
const std::vector &a,
const std::vector &b,
std::vector> &zipped)
{
for(size_t i=0; i
void unzip(
const std::vector> &zipped,
std::vector &a,
std::vector &b)
{
for(size_t i=0; i names {"Karl", "Martin", "Paul", "Jennie"};
std::vector score {45, 5, 14, 24};
// Zip the vectors together
std::vector> zipped;
zip(names, score, zipped);
// Sort the vector of pairs
std::sort(std::begin(zipped), std::end(zipped),
[&](const auto& a, const auto& b)
{
return a.second > b.second;
});
// Write the sorted pairs back to the original vectors
unzip(zipped, names, score);
for(size_t i=0; i