Assume I have some data a csv-Files like
ObjectName, PropertyA, PropertyB, PropertyC
"Name1", 3, 1, 4
"Name2", 1, 5, 9
"Name3", 2, 6, 5
...
and a typical question I want to answer would be
For which Object is PropertyX maximal?
I have two approaches for this and would be thankful for some Input.
Approach 1
I define a class like
struct Object {
std::String name;
int a;
int b;
int c;
};
Store the data in a class like
class ObjectCollection {
std::vector<Object> collection;
}
And provide two functions
size_t ObjectCollection::getMaxIndexOfA()
size_t ObjectCollection::getMaxIndexOfB()
size_t ObjectCollection::getMaxIndexOfC()
Now these Functions would essentially be the same and look like
size_t maxIndex = -1;
int max = std::numeric_limits<int>::min();
for (size_t i = 0; i < collection.size(); ++i) {
if (collection[i].a > max) {
maxIndex = i;
max = collection[i].a;
}
}
return maxIndex;
It bothers me that I would have to write and maintain the same code twice.
Approach 2
Store the data in a class like
class ObjectCollection {
std::vector<String> names;
std::vector<int> a;
std::vector<int> b;
std::vector<int> c;
}
Then I could provide methods like
const std::vector<int>& ObjectCollection::getA() const;
const std::vector<int>& ObjectCollection::getB() const;
const std::vector<int>& ObjectCollection::getC() const;
And use a single function to find the maximum which I have to call as
getMaxIndex( collection.getA() );
where size_t getMaxIndex(const std::vector<int>&) would be essentially the same as in approach 1.
I think I prefer the second approach, but it bothers me that in this case there is no class representing a single Object.
Is it weird/bad design to store the data as in the second approach? Is there another smart approach I didn't think about?
By the way, I am more concerned with the choice between these two approaches than the fact that I should probably use std::max_element to find the index.
std::max_element()which address exactly this problem? Especially the overload that takes a custom comparator. Don't contort your design when easy solutions are available in the standard library.