Reputation: 7288
I have input data like below,
//road graph: from and to
1 2
1 3
3 4
3 5
//next festive city: type and city_id
2 5
2 3
1 3
2 3
2 4
So far, I make 1 struct to represent both input types.
struct MainData{
int data;
int data_1;
};
int main()
{
/*code omitted*/
for(int i=0;i<n-1;i++){
cin>> highWays[i].data >> highWays[i].data_1;
}
for(i=0;i<m;i++)
{
cin>>queries[i].data>>queries[i].data_1;
}
/*code omitted*/
}
IMO, I don't think it's a good pratice, since the purpose of data
and data_1
is not clear. Though adding another struct might introduce larger file. Therefore, I'm confused whether to make 2 structs to differentiate those input types, which leads to better naming convention, or not. Any advice?
Upvotes: 0
Views: 221
Reputation: 726609
adding another struct might introduce larger file.
If this helps readability, it is a very good tradeoff. Adding another struct
to aid readability does not increase the size of your compiled program.
struct
s are primarily a compile-time artifact. The compiler uses them to know the size and field offsets. Unless your struct
comes with virtual member functions, adding a new struct
does not increase your program's run-time footprint. In cases when your struct
s are completely unrelated, there is no memory or CPU penalty for separating them out.
When your struct
s are related, though, C++ lets you have the best of both worlds: make a base class, derive from it, and provide member functions with descriptive names:
class GraphEdge {
protected:
int from;
int to;
GraphEdge(int f, int t) : from(f), to(t) {}
};
struct RoadEdge : public GraphEdge {
int fromRoad() { return from; }
int toRoad() { return to; }
RoadEdge(int f, int t) : GraphEdge(f, t) {}
};
struct CityEdge : public GraphEdge {
int fromCity() { return from; }
int toCity() { return to; }
CityEdge(int f, int t) : GraphEdge(f, t) {}
};
Upvotes: 3
Reputation: 5668
I think this is a very clear case: You are reading two very different tuples from your file(s). The first list contains graph edges with source and target indices, while the second list contains cities with a type and an ID.
You should be worrying about the readability, understandability and maintainability of your code first and foremost. The compiler will be able to optimize plenty; it is fairly unlikely that you will gain anything from the kind of premature optimization you are thinking of. So, following @dasblinkenlight's good answer (which he wrote before you enlightened us about the purpose of your data structures), I would recommend two different data structures:
class GraphEdge {
protected:
int from;
int to;
GraphEdge(int f, int t) : from(f), to(t) {}
};
class FestiveCity {
protected:
int city_type; // This should probably be an enum
int id;
FestiveCity(int t, int i) : city_type(t), id(i) {}
};
Upvotes: 1