• STL中deque


    以下学习一下STL中另一种序列容器——deque。

    deque表示double-ended queue,即双向队列,deque是通过作为动态数组的方式实现的,这样可以在两端插入元素。因此,deque可以在任何一个方向进行扩展。同时可以在中间插入元素。在开头或结尾处插入元素非常的快,然而在中间插入元素将会比较耗时间,因此需要移动队列中的元素。


    定义deque容器的类名为deque。类deque的定义以及deque对象的各种操作函数的实现包含在头文件<deque>中,因此,在程序中使用deque时,程序中必须包含如下语句:

    #include <deque>


    类deque中包含好几个构造器,因此,当声明一个deque对象时,可以通过各种方式进行初始化。如下表中提供的方式:


    除了之前介绍的所有序列容器通用的操作意外,下表还描述了用来管理deque容器的元素的操作。各个语句展示了如何使用某一个特定的函数,其中假设deq是一个deque容器


    下例展示了如何在程序中使用deque。

    #include <iostream>
    #include <deque>
    #include <algorithm>
    #include <iterator>
    
    using namespace std;
    
    int main()
    {
    	deque<int> intDeq;
    	ostream_iterator<int> screen(cout, " ");
    
    	intDeq.push_back(13);
    	intDeq.push_back(75);
    	intDeq.push_back(28);
    	intDeq.push_back(35);
    
    	cout << "intDeq: ";
    	copy(intDeq.begin(), intDeq.end(), screen);
    	cout << endl;
    
    	intDeq.push_front(0);
    	intDeq.push_back(100);
    
    	cout << "After adding two more "
    		<< "elements, one at the front " << endl
    		<< "	and one at the back, intDeq: ";
    
    	copy(intDeq.begin(), intDeq.end(), screen);
    	cout << endl;
    
    	intDeq.pop_front();
    	intDeq.pop_front();
    
    	cout << "After removing the first "
    		<< "two elements, " << endl
    		<< "	intDeq: ";
    	copy(intDeq.begin(), intDeq.end(), screen);
    	cout << endl;
    
    	intDeq.pop_back();
    	intDeq.pop_back();
    
    	cout << "After removing the last "
    		<< "two elements, " << endl
    		<< "	intDeq: ";
    	copy(intDeq.begin(), intDeq.end(), screen);
    	cout << endl;
    
    	deque<int>::iterator deqIt;
    	deqIt = intDeq.begin();
    	++deqIt;
    	intDeq.insert(deqIt, 666);
    
    	cout << "After inserting 666, "
    		<< "intDeq: ";
    	copy(intDeq.begin(), intDeq.end(), screen);
    	cout << endl;
    
    	intDeq.assign(2, 45);
    
    	cout << "After assigning two "
    		<< "copies of 45, intDeq: ";
    	copy(intDeq.begin(), intDeq.end(), screen);
    	cout << endl;
    
    	intDeq.push_front(-10);
    	intDeq.push_front(-999);
    
    	cout << "After inserting two "
    		<< "elements, one at the front " << endl
    		<< "	and one at the back, intDeq: ";
    	copy(intDeq.begin(), intDeq.end(), screen);
    	cout << endl;
    
    	return 0;
    }

    输出为:



  • 相关阅读:
    历史博文汇总
    Golang快速入门:从菜鸟到大佬
    网络1911、1912 DS第4次作业--批改总结
    [机器学习实战-Logistic回归]使用Logistic回归预测各种实例
    [机器学习实战-kNN算法]约会网站问题和手写数字系统实例
    SQL学习笔记(一)之基础语句
    Python学习笔记(九)之面向对象编程(下)
    Python学习笔记(八)之面向对象编程(上)
    Python学习笔记(七)之Python模块
    Python学习笔记(六)之函数式编程
  • 原文地址:https://www.cnblogs.com/riasky/p/3430770.html
Copyright © 2020-2023  润新知