fork(1) download
  1. #include <iostream>
  2. #include <vector>
  3. #include <string>
  4. #include <limits>
  5. using namespace std;
  6.  
  7. struct Object {
  8. std::string name;
  9. int a;
  10. int b;
  11. int c;
  12. };
  13.  
  14. class ObjectCollection {
  15. size_t getMaxIndexOf(int Object::* o); // private helper function
  16. public:
  17. std::vector<Object> collection;
  18. size_t getMaxIndexOfA();
  19. size_t getMaxIndexOfB();
  20. size_t getMaxIndexOfC();
  21. };
  22.  
  23. size_t ObjectCollection::getMaxIndexOf(int Object::* o) {
  24. size_t maxIndex = -1;
  25. int max = std::numeric_limits<int>::min();
  26. for (size_t i = 0; i < collection.size(); ++i) {
  27. if (collection[i].*o > max) {
  28. maxIndex = i;
  29. max = collection[i].*o;
  30. }
  31. }
  32. return maxIndex;
  33. }
  34. size_t ObjectCollection::getMaxIndexOfA() {
  35. return getMaxIndexOf(&Object::a);
  36. }
  37. size_t ObjectCollection::getMaxIndexOfB() {
  38. return getMaxIndexOf(&Object::b);
  39. }
  40. size_t ObjectCollection::getMaxIndexOfC() {
  41. return getMaxIndexOf(&Object::c);
  42. }
  43. int main() {
  44. ObjectCollection c;
  45. c.collection.push_back({"test0" , 1,2,3 });
  46. c.collection.push_back({"test1" , 2,1,4 });
  47. c.collection.push_back({"test2" , 3,1,2 });
  48. cout << c.getMaxIndexOfA() <<" " << c.getMaxIndexOfB() <<" " << c.getMaxIndexOfC() <<endl;
  49. return 0;
  50. }
Success #stdin #stdout 0s 4420KB
stdin
Standard input is empty
stdout
2 0 1