在很低的层面上,这些方法到底在做什么?
因为我注意到一些奇怪的行为,例如,如果我有一个带元素的向量...
2, 4, 6, 8
我说myVector.erase(myVector.begin() + 1);
,它给了我......
2, 6, 8, 8
然而,如果我再说myVector.insert(myVector.begin + 1, 3);
,它会给我......
2, 3, 6, 8
我没有得到任何重复的元素。如何在引擎盖下实施这些方法?
编辑:代码。
vector<int> v;
v.push_back(2);
v.push_back(4);
v.push_back(6);
v.push_back(8);
v.erase(v.begin() + 1);
cout << v[0] << v[1] << v[2] << v[3];
这给了我2688
答案 0 :(得分:6)
最初,矢量有4个元素
2, 4, 6, 8
因此它的大小等于4,容量(根据示例)也等于4.
陈述后
myVector.erase(myVector.begin() + 1);
删除元素4之后的所有元素都向左移动。
2, 6, 8, 8
但是现在大小等于3但容量仍然等于4.向量不会释放分配范围内未使用的内存。
再次发表声明
myVector.insert(myVector.begin + 1, 3);
向右移动所有元素以释放插入的poistion
2, 3, 6, 8
现在大小等于4,容量通常等于4。
您可以通过以下方式想象该过程
#include <iostream>
int main()
{
int a[] = { 2, 4, 6, 8 };
size_t size = 4;
size_t capacity = 4;
std::cout << "size = " << size << ", capacity = " << capacity << std::endl;
std::cout << "current state of the array: ";
for ( size_t i = 0; i < size; i++ ) std::cout << a[i] << ' ';
std::cout << std::endl;
std::cout << "The memory occupied by the array: ";
for ( int x : a ) std::cout << x << ' ';
std::cout << std::endl;
// removing the element with index 1
size_t i = 1;
for ( ; i + 1 < size; i++ ) a[i] = a[i+1];
--size;
std::cout << "\nsize = " << size << ", capacity = " << capacity << std::endl;
std::cout << "current state of the array: ";
for ( size_t i = 0; i < size; i++ ) std::cout << a[i] << ' ';
std::cout << std::endl;
std::cout << "The memory occupied by the array: ";
for ( int x : a ) std::cout << x << ' ';
std::cout << std::endl;
// inserting the element with index 1 and value 3
i = 1;
int value = 3;
size_t j = size;
for ( ; j != i; j-- ) a[j] = a[j-1];
a[j] = value;
++size;
std::cout << "\nsize = " << size << ", capacity = " << capacity << std::endl;
std::cout << "current state of the array: ";
for ( size_t i = 0; i < size; i++ ) std::cout << a[i] << ' ';
std::cout << std::endl;
std::cout << "The memory occupied by the array: ";
for ( int x : a ) std::cout << x << ' ';
std::cout << std::endl;
}
程序输出
size = 4, capacity = 4
current state of the array: 2 4 6 8
The memory occupied by the array: 2 4 6 8
size = 3, capacity = 4
current state of the array: 2 6 8
The memory occupied by the array: 2 6 8 8
size = 4, capacity = 4
current state of the array: 2 3 6 8
The memory occupied by the array: 2 3 6 8