Sort a 3D std::vector based on values in a 1D std::vector

I have a 3D vector :

vector<vector<vector<char>>> children;

this vector contains multiple 2D vectors and I would like to sort them based on a 1D vector:

vector<int> score;

each 2D vector in children is associated with a value in score. I have tried multiple similar questions but with no luck, so I was wondering how different the case of 3D vectors or is it even possible to sort with a vector of a different dimension in the first place?

I’m still fairly new to C++.


If your goal is to sort the scores and maintain the sorted scores with their relative position in the 3D vector, as the comment suggested and based on this answer you can sort an array of indices that are based on the score criteria.

After sorting the indices, you use the indices to “point to” each sorted item in the 3D vector.

Here is an example:

#include <algorithm>
#include <vector>
#include <numeric>

int main()
    std::vector<std::vector<std::vector<char>>> children;
    std::vector<int> score;
    // Assume score and children have values
    // Sort the 3D vector based on the scores     
    // Set up the index vector
    std::vector<int> index(score.size());
    std::iota(index.begin(), index.end(), 0);
    // sort the indices based on the scores
    std::sort(index.begin(), index.end(), [&](int n1, int n2)
    { return score[n1] < score[n2]; });
    // Do something with the "sorted" 3D vector
    // The first sorted child is children[index[0]], the second is children[index[1]], etc.

Note that the linked answer has a thorough explanation of why and when this technique is used.

Leave a Reply

Your email address will not be published. Required fields are marked *