简体   繁体   中英

std::sort on vector of vector

I'm actually trying to sort a vector of Descriptor basing on a vector included in the Descriptor

float           xi, yi;     // Descriptor location
vector<double>  fv;         // The feature vector

(here the vector named fv) What I want to do is to search in the vector of Descriptor (I will name it Vec_Desc for more clarity from now) the dimension that have the most variance to do so, I use :

double Tree::_get_mean(vector<Descriptor>& vec, int indice)
{
    double sum = 0;
    int size = vec.size();
    for (int i = 0; i < size; i++) {
        sum += vec[i].fv[indice];
    }
    sum /= size;
    return sum;
}

double Tree::_get_variance(vector<Descriptor>& vec, int indice)
{
int size = vec.size();
double var = 0;
double mean = _get_mean(vec, indice);
    for (int i = 0; i < size; i++) {
        var += ((vec[i].fv[indice] - mean) *  (vec[i].fv[indice] - mean)) / size;
    }
    return var;
}

int Tree::choose_dimension(vector<Descriptor>& vec)
{
    double var = _get_variance(vec, 0);
    int indice = 0;
    for (int i = 1; i < vec[0].fv.size(); i++) {
         if (var > _get_variance(vec, i)) {
            var = _get_variance(vec, i);
            indice = i;
        }
    }
}

Then I want to sort the vec_desc based on the dim I found. Tried to do like this :

class _compare {
    int step;
public: 
     _compare(int s) : step(s) {}

    bool operator()(const vector<double>& p1, const vector<double>& p2) {
        return p1[step] < p2[step];
    }
};

void Tree::_sort_vector(vector<Descriptor>& vec, int i)
{
    std::sort(vec.begin(), vec.end(), _compare(i));
}

void Tree::sort_vector(vector<Descriptor>& vec)
{
    _sort_vector(vec, choose_dimension(vec));
}

But with this, I will sort vec_desc using his own values, and not the values contained in the fv's... How can I do this?

Your comparator is incorrect - since you are sorting vector<Descriptor> it has to compare two instances of Descriptor not vector<double> :

class _compare {
    int step;
public: 
     _compare(int s) : step(s) {}

    bool operator()(const Descriptor& d1, const Descriptor& d2) const {
        return d1.fv[step] < d2.fv[step];
    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM