c++ vector 常用函数示例解析

c++ vector 常用函数

Just like arrays, vectors use contiguous storage locations for their elements, which means that their elements can also be accessed using offsets on regular pointers to its elements, and just as efficiently as in arrays. But unlike arrays, their size can change dynamically, with their storage being handled automatically by the container.

vector也是一个数组但是它的占用的内存大小是动态变化的。当vector占用的内存满了之后,就要重新分配内存,并且赋值原来的所有元素,为了避免频繁的重新分配内存,迁移数据。vector实际分配的内存比你需要的内存多。比如你有10个int的数据在vector中,vector实际占用的内存是20个int的内存, 当你数据占用超过实际占用内存的比例的时候,vector就会自动重新分配内存,迁移数据. vector实际占用的内存可以用capacity()来查看

#include
#include
using namespace std;
int main(){
  vector ans;
  for(int i=0; i<10; i++) ans.push_back(i);
  ans.erase(ans.begin()+2);
  cout<<"擦除第三个数字:";
  for(int j=0; j temp(5, -1);
  cout< 
 

此外可以配合#include库中的unique函数来删除vector中的重复元素

vector ans;
ans.erase(unique(ans.begin(), ans.end()), ans.end());

到此这篇关于c++ vector 常用函数示例解析的文章就介绍到这了,更多相关c++ vector 常用函数内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(c++ vector 常用函数示例解析)