c++ - Sorting using objects in vectors -
i have function computing , set value returned vector.
#include <vector> #include <algorithm> #include <iostream> void vectorloop(vector<classname>& vector) { float tempfloatvariable = 0.0; int count = 0; int update = 0; while (count != vector.size()) { if (vector[count].getvalue() == 100.0) //i hardcode can check if value empty or not { //code set of variable vector's memory's object tempfloatvariable = anotherclass.formula //does computing , return value //code gets value object overloading //code gets value object overloading //code gets value object overloading vector[count].setvalue(tempfloatvariable); update++; } else { count++; } } cout << "computation completed! (" << update << " record(s) updated)" << endl; }
after of computing done, want sort them highest lowest, base on value, have no idea how so, tried hard code it, pulling values out manually 1 1 comparison, kept failing. , defeat purpose of using vector, there many examples of sorting using vector, 90% of int values stored in vectors.
as igortandetnik said: do
std::sort(vector.begin(), vector.end(), [](const pointtwod& a, const pointtwod& b) { return a.getcivindex() > b.getcivindex(); });
which use result lambda sort vector , should want.
to print objects in vector should this:
for(int = 0; < vector.size(); i++) { std::cout << vector[i] << std::endl; //or whatever printing function is. }
which iterate on objects in vector and, should in descending order sort, print them out in descending order wanted.
edit:
for non c++11 users: can define function comparison
bool compare(const pointtwod& a, const pointtwod& b) { return a.getcivindex() > b.getcivindex(); }
and use instead of lambda. this:
std::sort(vector.begin(), vector.end(), compare);
Comments
Post a Comment