Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference in memory layout of vector of pairs and vector of structs containing two elements - C++/STL

Tags:

c++

memory

stl

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;
 };
like image 396
smilingbuddha Avatar asked Feb 22 '23 02:02

smilingbuddha


2 Answers

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.

like image 131
Gustavo Maciel Avatar answered Apr 19 '23 22:04

Gustavo Maciel


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.

like image 36
Shahbaz Avatar answered Apr 20 '23 00:04

Shahbaz