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 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
// I just like shorter types, so I typedef
// but choose a name you prefer
typedef std::pair< std::size_t, double > RowVal;
// this is a comparison function object to be used by std::sort
struct Comparator // call this what you like
{
// in case you're not accustomed to typedefs, remember RowVal is the same as your std::pair
// this is what sort expects, an overload of the function operator (), it's what makes this struct a function object
bool operator ()( const RowVal & rv1, const RowVal & rv2 )
{
// note: this is object traditionally answers "is less than"
// but we want this reversed, so we answer what we prefer for
// a reverse sort
return ( get<1>( rv1 ) > get<1>( rv2 ) );
}
};
int main()
{
std::vector<std::vector<double>> matrice
{
{1.05, -8.05, 1.0, 8.58, 3.04},
{15.05, 8.05, 7.05, 8.58},
{11.05, 88.05, 7.06},
{-12.05, -8.05}
};
typedef std::vector< RowVal > RowVec;
// even though this says RowVec, it's a typedef of exactly what
// you wrote before, so nothing has changed here
RowVec indexLargestVec;
indexLargestVec.reserve(matrice.size());
for (const std::vector<double>& row : matrice)
{
const auto iter = std::max_element(row.cbegin(), row.cend());
indexLargestVec.emplace_back(std::distance(row.cbegin(), iter), *iter);
}
std::sort( indexLargestVec.begin(), indexLargestVec.end(), Comparator() );
std::size_t row = 0;
for(const std::pair < std::size_t, double>& indexElement: indexLargestVec)
std::cout << "The "<< row++ <<" largest of " << row++ << " "
<< indexElement.second
<< " and index " << indexElement.first << '\n';
return 0;
}
|