C++ STL学习——deque

版权声明:本文为博主原创文章,欢迎分享到其它技术社区,分享请标明出处: https://blog.csdn.net/CHENYUFENG1991/article/details/52454957

       在数据结构中还有一种很常见的队列叫做双端队列,我们在上一篇博客《C++ STL学习——queue》中讲到的队列queue是一种最标准的队列,只能在尾部插入数据,在头部删除数据。而今天我们讲到的deque分别可以在两端进行插入与删除,可以说用起来更加的灵活。示例代码上传至 https://github.com/chenyufeng1991/STL_deque 。

(1)创建一个deque

    deque<int> deque1;
    deque<int> deque2(deque1);
    deque<int> deque3(10);
    deque<int> deque4(10,0);

(2)deque尾部插入数据

    deque1.push_back(1);
    deque1.push_back(2);
    deque1.push_back(3);
    deque1.push_back(4);
    PrintDeque(deque1);


(3)deque头部插入数据

    deque1.push_front(5);
    deque1.push_front(6);
    PrintDeque(deque1);

(4)查看头部元素、尾部元素和某位置元素

    cout << "头部元素为:" << deque1.front() << endl;
    cout << "尾部元素为:" << deque1.back() << endl;

    cout << "某位置的元素为:" << deque1.at(2) << endl;
    cout << "某位置的元素为:" << deque1[2] << endl;


(5)使用迭代器在某位置插入元素

// 使用迭代器插入或删除元素
    deque<int>::iterator iterInsert = deque1.begin();
    iterInsert = iterInsert + 2;
    deque1.insert(iterInsert, 99);
    PrintDeque(deque1);


(6)使用迭代器在某位置删除元素

    deque<int>::iterator iterErase = deque1.begin();
    iterErase = iterErase + 2;
    deque1.erase(iterErase);
    PrintDeque(deque1);


(7)size(), max_size()

    cout << "deque1.size = " << deque1.size() << endl;
    cout << "deque1.max_size = " << deque1.max_size() << endl;


(8)头部、尾部删除元素

    deque1.pop_back();
    PrintDeque(deque1);

    deque1.pop_front();
    PrintDeque(deque1);


(9)交换两个deque

    // 交换两个deque
    deque<int> dequeSwap;
    dequeSwap.push_back(11);
    dequeSwap.push_back(22);
    dequeSwap.push_back(33);

    cout << "deque1:" ;
    PrintDeque(deque1);
    cout << "dequeSwap:";
    PrintDeque(dequeSwap);

    deque1.swap(dequeSwap);
    cout << "deque1:" ;
    PrintDeque(deque1);
    cout << "dequeSwap:";
    PrintDeque(dequeSwap);


(10)判断deque是否为空

    cout << "deque是否为空:" << deque1.empty() << endl;
    deque1.clear();
    cout << "deque是否为空:" << deque1.empty() << endl;
    PrintDeque(deque1);


(11)迭代器打印deque

void PrintDeque(deque<int> pDeque)
{
    cout << "deque元素为:";
    deque<int>::iterator dequeIter;
    for (dequeIter = pDeque.begin(); dequeIter != pDeque.end(); dequeIter++)
    {
        cout << *dequeIter << " ";
    }

    cout << endl;
}

展开阅读全文

没有更多推荐了,返回首页