C++STL

STL

Vector实现

deque

  • 适合双端操作
  • 不适合遍历,每次都会检查内存边界,开销大
  • 头尾插入删除效率更高,中间任意位置操作比其他容器慢
  • Constructor:构造器
// Constructor
std::deque<int> first;                                // empty deque of ints
std::deque<int> second (4,100);                       // four ints with value 100
std::deque<int> third (second.begin(),second.end());  // iterating through second
std::deque<int> fourth (third);                       // a copy of third
// the iterator constructor can be used to copy arrays:
int myints[] = {16,2,77,29};
std::deque<int> fifth (myints, myints + sizeof(myints) / sizeof(int) );
  • operator =:相同结构的deque替换
std::deque<int> first (3);    // deque with 3 zero-initialized ints
std::deque<int> second (5);   // deque with 5 zero-initialized ints
second = first;
first = std::deque<int>();
>out: first.size()=0,second.size()=3
  • Iterator:begin(),end()
  • Capacity:
    • size():返回大小;
    • max_size():deque可以容纳的最大数,返回值为unsigned int类型
    • resize(size_type n, const value_type& val):重置大小,若指定val,则以val填充,否则以任意元素填充,小于n的则删除
    • empty():返回bool值,空->true,非空->false
  • Modifier:
    • push_back(value_type&& val)
    • push_front(value_type&& val)
    • pop_back
    • pop_front
    • insert:在特定pos插入val,插入后,之前的迭代器失效
    • erase:特定pos删除,或一段删除,左闭右开
    • swap(deque &x):二者交换,类型 应相同
    • clear():清除所有元素
    • emplace:与insert相似,但效率高些,emplace是直接构造元素,不需要调用拷贝,无临时变量.
    • emplace_front,emplace_back:类似push_front/back.
std::deque<int> mydeque;
// set some initial values:
for (int i=1; i<6; i++) mydeque.push_back(i); // 1 2 3 4 5
std::deque<int>::iterator it = mydeque.begin();
++it;
it = mydeque.insert (it,10);                  // 1 10 2 3 4 5
// "it" now points to the newly inserted 10
mydeque.insert (it,2,20);                     // 1 20 20 10 2 3 4 5
// "it" no longer valid!
it = mydeque.begin()+2;
std::vector<int> myvector (2,30);
mydeque.insert (it,myvector.begin(),myvector.end());
                                                // 1 20 30 30 20 10 2 3 4 5
                                            
std::deque<int> foo (3,100);   // three ints with a value of 100
std::deque<int> bar (5,200);   // five ints with a value of 200
foo.swap(bar);  
foo.clear();
posted @   ddkimser  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示