Bonjour,
j'ai fait une classe pour trier des std::vector<double>, que j'aimerais pouvoir utiliser comme suit :
1 2 3 4 5 6 7 8 9 10
|
#include "sorter.h"
std::vector<double> values;
std::vector<int> indices, ranks;
initialize(values); // remplit values avec des double
Sorter mySorter() // instancie le trieur
mySorter.sort(values, indices); // indices récupère les indices des values décroissants
mySorter.rank(values, ranks); // Autre retour possible : ranks[i] vaut le rang de value[i] |
Voici les fichiers de ma classe :
sorter.cpp :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include "sorter.h"
Sorter::Sorter()
{
}
Sorter::Sorter(vector<double>& values, vector<int>& indices)
{
m_values = &values;
sort (values, indices);
}
void Sorter::rank(vector<double>& values, vector<int>& ranks)
{
int n = values.size();
if (ranks.size() != n)
ranks.resize(n);
vector<int> indices;
sort(values, indices);
double lastVal = values[indices[0]];
int lastIndex = 0;
for (int i = 2; i < n; i++) {
if (values[indices[i]] = lastVal)
ranks[indices[i]] = lastIndex;
else {
ranks[indices[i]] = i;
lastIndex = i;
}
lastVal = values[indices[i]];
}
}
void Sorter::sort(vector<double>& values, vector<int>& indices)
{
int n = values.size();
if (indices.size() != n)
indices.resize(n);
for (int i = 0; i< n; i++)
indices[i] = i;
m_values = &values;
std::sort(indices.begin(), indices.end(), *this);
}
bool Sorter::operator()(int i, int j)
{
if((*m_values)[i] > (*m_values)[j])
return true;
return false;
}
Sorter::~Sorter()
{
} |
sorter.h :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| #ifndef _sorter_h
#define _sorter_h
#include <functional>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
class Sorter : public std::binary_function<int, int, bool>
{
public:
Sorter();
Sorter(vector<double>&, vector<int>&);
void rank(vector<double>&, vector<int>&);
void sort(vector<double>&, vector<int>&);
bool operator()(int i, int j);
~Sorter();
private:
vector<double>* m_values;
};
#endif |
On en vient à ma question :
Le tri fonctionne bien quand je l'execute dans un constructeur, mais pourquoi le code suivant ne compile-t-il pas (sous visual studio express 2008) ?:
1 2
| Sorter mySorter(values, indices); // OK
mySorter.sort(values, indices); // ne compile pas |
error C2228: la partie gauche de '.sort' doit avoir un class/struct/union
Partager