deque
- Deque is double-ended queue
Initialization
#include <iostream>
#include <deque>
template <class T>
void display(T it, T end)
{
for(; it != end; ++it)
std::cout<<*it<<" ";
std::cout<<std::endl;
}
int main(int argc, char *argv[])
{
std::deque<int> a = {1, 2, 3, 4};
std::deque<int> b(10);
std::deque<int> c(10, 100);
std::deque<int> d(c.begin(), c.end());
std::deque<int> e(d);
int array[] = {10, 20, 30, 40, 50};
std::deque<int> f(array, array+sizeof(array)/sizeof(int));
//operator =
a = f;
display(a.begin(), a.end());
return 0;
}
Retrieve Deque
#include <iostream>
#include <deque>
int main(int argc, char *argv[])
{
std::deque<int> a = {1, 2, 3, 4};
std::cout<<a[1]<<std::endl;
std::cout<<a.at(1)<<std::endl;
std::cout<<a.front()<<std::endl;
std::cout<<a.back()<<std::endl;
std::cout<<*(a.begin()+3)<<std::endl;
std::cout<<a.begin()[2]<<std::endl;//might not be safe
auto it = a.begin();
std::advance(it, 2);
std::cout<<*it<<std::endl;
return 0;
}
Insert and Delete
#include <iostream>
#include <deque>
template <class T>
void display(T it, T end)
{
for(; it != end; ++it)
std::cout<<*it<<" ";
std::cout<<std::endl;
}
int main(int argc, char *argv[])
{
std::deque<int> a = {1, 2, 3, 4};
//push_back
a.push_back(10);
//push_front
a.push_front(20);
//insert, insert new elements before the elements at the specified position
a.insert(a.begin()+1, 10);
//erase
a.erase(a.begin()+1);
//pop_back
a.pop_back();
//pop_front
a.pop_front();
//clear
a.clear();
display(a.begin(), a.end());
return 0;
}
Capacity
#include <iostream>
#include <deque>
template <class T>
void display(T it, T end)
{
for(; it != end; ++it)
std::cout<<*it<<" ";
std::cout<<std::endl;
}
int main(int argc, char *argv[])
{
std::deque<int> a = {1, 2, 3, 4};
a.pop_back();
a.resize(2);
a.shrink_to_fit();
std::cout<<"Size: "<<a.size()<<std::endl;
std::cout<<"Max_size: "<<a.max_size()<<std::endl;
display(a.begin(), a.end());
return 0;
}
Memory
Reference