STL 笔记: deque vector string

本文介绍了STL中的deque和vector的区别,强调deque在元素插入和删除效率上的优势,以及它们内存分配的特性。同时,详细讲解了std::string的substr、find、rfind、find_first_of和find_last_of等方法的使用,提供了相关实例来帮助理解。
摘要由CSDN通过智能技术生成

英文描述参考: www.cplusplus.com 部分解释参考:stackoverflow

std deque 和 vector

They provide a functionality similar to vectors, but with efficient insertion and deletion of elements also at the beginning of the sequence, and not only at its end. But, unlike vectors, deques are not guaranteed to store all its elements in contiguous storage locations: accessing elements in a deque by offsetting a pointer to another element causes undefined behavior.

deque和vector非常相似,不同点在于deque支持在头尾插入和删除,而且在两端插入和删除不会导致重新分配空间。vector只能在末尾实现插入和删除。deque不保证连续性存储空间,指针偏置可能导致获取不到元素。

根据以上性质可知,deque除了有push_back,pop_back还有push_front,pop_front。

vector::size()和deque::size()都返回size_type类型的数据。

vector::front()和vector::begin()的区别在于前者是reference 而后者是iterator。

下面这里例子说明了deque分配内存时是不连续的,如果声明std::vector myvector; 那么&*it&*(it-1)相差4(int),如果声明std::deque myvector; 那么&*it&*(it-1)不一定相差4。

#include <iostream>
#include <vector>
#include <deque>

int main ()
{
  std::deque<int> myvector;
  std::deque<int>::iterator it;

  // set some content in the vector:
  for (int i=0; i<128; i++) myvector.push_back(i);

  std::cout << "size: " << (int) myvector.size() << '\n';
  it=myvector.end();
  std::cout << "it: " << &*it << '\n';
  it--;
  std::cout << "it: " << &*it << '\n';
  std::cout << "max_size: " << (int) myvector.max_size() << '\n';
  return 0;
}

deque::push_front的例子

// deque::push_front
#include <iostream>
#include &l
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值