之前在介绍vector的初始化的时候有介绍到容器的push_back操作,push_back基本所有容器都支持,而push_front则是有的支持有的不支持。insert和push_back一样,所有容器都支持。
这里简单介绍一下三种不同添加元素的方式。
1.push_back
这个之前有介绍,是在容器尾部添加新的元素
vector<int> arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
这样插入元素后容器arr内部元素分别是1,2,3
(和push_back()成对的pop_back()的作用的删除末尾的元素)
2.push_front
从字面可以看出这个函数和push_back相反,它是在容器开头增加新的元素,因为容器特性的原因,有些不支持这个操作,比如vector,因为执行效率的原因(时间复杂度)。而list则支持这个操作,如下:
list<int> lt;
lt.push_front(1);
lt.push_front(2);
lt.push_front(3);
这样插入过后,lt内部元素按照顺序就是3,2,1,因为是从头部插入数据,所以后插入的在前面。相当于链表的头插法操作。
3.insert
push_back用于在尾部插入数据,push_front用于在头部插入数据,此时当然需要一个可以在任意位置插入数据的功能,insert就提供了这个功能。每个insert函数都接受一个迭代器作为其第一个参数。迭代器指出了在容器中什么位置放置新元素,他可以指向容器中任何位置,包括容器尾部之后的下一个位置。对于不支持push_front操作的容器,可以用insert来实现,如
vector<string> svc;
svc.insert(svc.begin(),"front");
这个操作相当于push_front,在容器开头添加一个新元素。
除了第一个迭代器参数之外,insert函数还可以接受更多的参数,这与容器构造函数类似,其中一个版本接受一个元素数目和一个值,他将指定数量的元素添加到指定位置之前,这些元素都按定值初始化,如:
vector<int> sec{1,2,3};
sec.insert(sec.end(),5,4); //在容器尾部添加5个4,相当于整体为1,2,3,4,4,4,4,4
同时insert还可以接受一堆迭代器或一个初始化列表,将给定范围中的元素插入到指定位置之前
vector<string> v = {"Go to hell", "Donald Trump!", "God damn you!"};
vector<string> svc = {"Political buffoon!"};
svc.insert(svc.begin(),v.end()-2,v.end()); //将v的最后两个元素插入到svc的第一个元素之前
svc.insert(svc.end(),{"M","y ","l","l~"}); //将这个初始化列表插入到svc的尾部
insert的返回值也可以有效利用,如下面这个循环:
list<string> listFrom = {"1","2","3"};
list<string> listTo;
auto iter = listTo.begin();
for(string word:listFrom)
{
iter = listTo.insert(iter, word); //此操作等价于push_front
}
循环之前将iter初始化为listTo.begin(),循环内部,每次调用insert会返回插入后元素的位置,即iter始终指向容器首元素,如此重复循环,最终效果,listTo容器内部元素为{"3","2","1"},刚好与listFrom相反