mercredi 6 décembre 2017

Sort a vector with another vector using lambda function

In the code below, I get segmentation fault. I think the problem is with indexing but I don't understand why. Is it possible to use std::sort and lambda function to sort a vector based on another vector?

#include<iostream>
#include<algorithm>
#include<vector>
#include<string>

int main()
{
    std::vector<std::string> A = {"b", "a", "c"};
    std::vector<int> B = {2, 1, 3};

    std::sort(std::begin(A), std::end(A),
            [&](const std::string& t1, const std::string& t2)
            {
            return B[&t1-A.data()] > B[&t2-A.data()]; // problem could be here!
            });

    std::cout << A[0] << std::endl;
    std::cout << A[1] << std::endl;
    std::cout << A[2] << std::endl;

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire