17

C++ 中的 vector 和 Java 中的 ArrayList 的构造函数的区别

 3 years ago
source link: https://xie.infoq.cn/article/9651cff33cfa48cd4b63f2f94
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

前言:之前一直存在一个理解误区,以为C++中的 vector 存在一个构造函数可以为 vector 对象预分配空间,在调试代码时,才发现是自己理解错了,接收一个整数的 vector 的构造函数并不是预分配空间,而是直接添加了元素,因此写一篇文章来记录一下。

C++中的vector

接收一个整数的 vector 的构造函数实际上是直接向 vector 对象中添加了元素:

vector<string>arr(10);
cout<< arr.size() <<endl;// 10

如果要给 vector 对象预分配空间的话,必须使用 reserve() 成员函数:

vector<string> arr;
arr.reserve(10);
cout<< arr.size() <<endl;// 0
cout<< arr.capacity() <<endl;// 10

Java中的ArrayList

而Java中的 ArrayList 也有一个类似的构造函数,接收一个整数:

public ArrayList ( int initialCapacity)

与C++中的 vector 不同,该构造函数是会预分配空间的,而不是直接添加元素:

ArrayList<String> arr =newArrayList<>(10);
System.out.println(arr.size());// 0

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK