C ++ Vector push_back()的详细信息 [英] Details of C++ Vector push_back()

查看:59
本文介绍了C ++ Vector push_back()的详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调试程序,但这样做与我对C ++向量push_back()函数的理解背道而驰.

I'm trying to debug a program, and in doing so have bumped up against my understanding of the C++ vector push_back() function.

为了说明我的观点,我编写了以下简短程序:

To illustrate my point, I've written the following short program:

#include <iostream>
#include <vector>
#include <cstdlib>

using std::cout;
using std::endl;
using std::vector;

class Test {
private:
  int mTestMember;
public:
  Test(int val);
  Test(const Test&);

  int GetValue() const;
};

Test::Test(int val)
{
  cout << "Constructor\n";
  mTestMember = val;
}

Test::Test(const Test& test)
{
  cout << "Copy Constructor\n";
  mTestMember = test.mTestMember;
  cout << "mTestMember: " << mTestMember << endl;
}

int main(){

  vector<Test> tests;
  tests.push_back(Test(int(5)));
  cout<< endl;
  tests.push_back(Test(int(6)));
  cout << endl;
  tests.push_back(Test(int(7)));

  return(0);
}

如果我编译运行,将得到以下输出:

and if I compile and run, I get the following output:

Constructor
Copy Constructor
mTestMember: 5

Constructor
Copy Constructor
mTestMember: 6
Copy Constructor
mTestMember: 5

Constructor
Copy Constructor
mTestMember: 7
Copy Constructor
mTestMember: 5
Copy Constructor
mTestMember: 6

在push_back()函数的过程中,似乎执行了该对象的副本,该对象作为参数传递给push_back()函数(我已经知道),然后其余预先存在的元素也会从头开始复制到新向量中.

It would appear that, in the process of the push_back() function, a copy is performed of the object that is passed as the argument to the push_back() function (which I already knew), and then the rest of the elements that were present in the pre-existing are also copied to the new vector starting from the front.

我对这一过程的理解正确吗?

Am I correct in my understanding of the process?

推荐答案

std :: vector 将其元素存储在数组中.数组始终具有固定的大小,因此,如果您继续向 std :: vector 中添加元素,则其底层数组最终将被填满.当数组已满并且您添加另一个元素(通过 push_back 或另一个添加新元素的成员函数)时,它必须:

std::vector stores its elements in an array. An array always has fixed size, so if you keep adding elements to a std::vector, its underlying array will eventually fill up. When the array is full and you add another element (via push_back or another member function that adds new elements), it must:

  1. 创建一个更大的新数组,
  2. 将元素从旧数组复制或移动(*)到新数组,
  3. 将新元素插入新数组,然后
  4. 销毁旧数组

此过程称为重新分配. std :: vector 的正确实现应按指数大小调整数组的大小.Visual C ++ std :: vector 实现使用1.5倍的增长因子.其他实现可能会使用不同的增长因子.

This process is called reallocation. A correct implementation of std::vector should resize the array exponentially. The Visual C++ std::vector implementation uses a growth factor of 1.5x; other implementations may use a different growth factor.

(*)C ++ 11添加了对 moving 对象的支持.

(*) C++11 adds support for moving objects.

这篇关于C ++ Vector push_back()的详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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