Malium
Malium

Reputation: 79

STL containers vs Structs

I would like to know what is better to use and why:

Before I used to create types with STL Containers, but recently I've found that APIs use struct like types, which I think is due to the use of C instead of C++, but I want to know what is best in terms of performance and memory.

Before:

typedef std::tuple<std::string, int, int, bool> SomeType;

Now:

typedef struct tagSomeType { std::string sVar; int iVar, iVar2; bool bVar; } SomeType;

Thank you

[EDIT] I put this example of tuple to make it visible, but for example

typedef std::pair<int, int> iCoord; /* VS */ struct iCoord{int x, y;};

Seems that the only diference is that struct has more readability than STL Container

Upvotes: 1

Views: 681

Answers (2)

Frank Puffer
Frank Puffer

Reputation: 8215

There is no significant difference in memory usage and performance. So the main criterion should be readability.

One difference is that in a struct, each element has a name, which is not the case for tuples. Especially if you have more that 2 or 3 elements, this can make structs more readable.

By the way, your struct declaration is C style. In C++ you can write it like this:

struct SomeType { std::string sVar; int iVar, iVar2; bool bVar; };

Upvotes: 3

grigor
grigor

Reputation: 1624

There is no unique answer to this question and it depends on your situation. My own opinion is that if you have more than two variables you should use struct, unless you have a strong reason not to. In struct you can give names to your variables, so that you don't have to memorize that number 1 is this and number 2 is that.

Upvotes: 2

Related Questions