Is the layout in memory of test1
and test2
the same?
std::vector<std::pair<int,int> > test1;
std::vector<mystruct> test2;
where mystruct is defined as:
struct mystruct{
int a;
int b;
};
If you see on the cplusplus.com, you'll see that this is the struct of a pair:
template <class T1, class T2> struct pair
{
typedef T1 first_type;
typedef T2 second_type;
T1 first;
T2 second;
pair() : first(T1()), second(T2()) {}
pair(const T1& x, const T2& y) : first(x), second(y) {}
template <class U, class V>
pair (const pair<U,V> &p) : first(p.first), second(p.second) { }
}
Exactly the same, i would say, except some facts: Well, beginning with the fact that pairs are compatible with the std containers and all that, for example, maps. Also, the pairs are already made, and already have constructors for you.
EDIT: I also forgot to mention that you'll have std::make_pair for you, that allow you skipping allocating memory and making your own pair in a struct and you too have some comparison and assignment operators defined.
Logically, std::pair<int, int>
should be defined like that also.
There is however nothing about that on the standard and it is completely unguaranteed. You could take a look at the header files in your compiler to confirm that, but that doesn't prove anything.
Note: If you think it is absurd to be otherwise, I can give you an example how it could be defined otherwise. Imagine in the other stl template classes that use std::pair
, they feel it would be convenient (for any reason), to have a pointer to the node containing the pair, in the pair. This way, they could, internally, add a pointer to the pair class while not violating any rules. Your assumption would then cause havoc. I would say it is unlikely for them to do such a thing, yes, but as long as they are not forced to that layout, anything can happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With