std :: vector内部 [英] std::vector internals

查看:166
本文介绍了std :: vector内部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用什么数据结构实现 std :: vector ?当我写

  void f(int n){
std :: vector< int& v(n)。
...
}

向量 v 向量向量 c>对象将在堆栈上分配,并在内部包含指向上的元素的开头



堆上的元素赋予向量类按需增长和收缩的能力。



堆栈上使用向量可以使对象在外出时受到破坏



对于您的 [] 问题,向量 class overloads [] 运算符。我会说内部是基本上做这样的事,当你做 array [1]

  return *(_ Myfirst +(n * elementSize))

向量 _Myfirst 下跟踪其内部堆的开始。



当您的向量开始填满时,它会分配更多的内存。



请注意 vector 继承自 _Vector_val ,其中包含以下成员:

  pointer _Myfirst; //指向数组开头的指针
pointer _Mylast; //指向当前结束序列的指针
指针_Myend; //指向数组结尾的指针
_Alty _Alval; //值
的分配器对象


How is std::vector implemented, using what data structure? When I write

void f(int n) {
  std::vector<int> v(n);
  ...
}

Is the vector v allocated on stack?

解决方案

The vector object will be allocated on the stack and will internally contain a pointer to beginning of the elements on the heap.

Elements on the heap give the vector class an ability to grow and shrink on demand.

While having the vector on the stack gives the object the benefit of being destructed when going out of scope.

In regards to your [] question, the vector class overloads the [] operator. I would say internally it's basically doing something like this when you do array[1]:

return *(_Myfirst+ (n * elementSize))

Where the vector keeps track of the start of it's internal heap with _Myfirst.

When your vector starts to fill up, it will allocate more memory for you. A common practice is to double the amount of memory needed each time.

Note that vector inherits from _Vector_val, which contains the following members:

pointer _Myfirst;   // pointer to beginning of array
pointer _Mylast;    // pointer to current end of sequence
pointer _Myend; // pointer to end of array
_Alty _Alval;   // allocator object for values

这篇关于std :: vector内部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆