Examples of basic operations for stack queue and vector in c++

  • 2020-05-27 06:49:40
  • OfStack

preface

These days in contact with the topic of search, bfs is basically used in the queue, on the way to learn the data structure of the stack, queue. This article will introduce the basic operation of stack, queue and vector in c++ in detail, and share it for your reference and study.

The basic operations of stack are:

Push, as in the example: s.push(x);

Push, as in the example: s.pop(); Note that the out-of-stack operation simply removes the top element of the stack and does not return it.

Access the top of the stack, as in the example: s.top()

Judge empty stack, as in the example: s.empty() , when the stack is empty, true is returned.

The number of elements in the access stack, as shown in the following example: s.size() .

The basic operations of queue are:

Join the team, as in: q.push(x); Connect x to the end of the queue.

Out of the line, as in: q.pop(); The first element of the pop-up queue, note, does not return the value of the ejected element.

Access the header element, as in the example: q.front() , the element that is pushed into the queue first.

Access the tail element, as in the example: q.back() , the last element to be pushed into the queue.

Judge the queue is empty, as shown in the following example: q.empty() , when the queue is empty, true is returned.

The number of elements in the access queue, as shown in the following example: s.pop();0

The basic operations of vector are:

Insert digits at the end: vec.push_back(a);

Using subscripts to access elements, cout<<vec[0]<<endl; Remember the index starts at 0.

Use iterators to access elements.


vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
cout<<*it<<endl;

Insert element: vec.insert(vec.begin()+i,a); Insert a before the i+1 element;

Delete element: vec.erase(vec.begin()+2); Delete the third element

vec.erase(vec.begin()+i,vec.end()+j); Delete interval [i, j-1]; The interval starts at 0

Vector size: vec.size();

Empty: vec.clear();

Note:

Flip the element using reverse: a header file is required #include<algorithm>

reverse(vec.begin(),vec.end()); Flip the element (in vector, if you need two iterators in one function, you don't include either.)

Sort using sort: header files are required s.top()0 .

s.top()1 (the default is in ascending order, that is, from small to large).

The sort comparison function can be overwritten to compare in descending order, as follows:

Define the sort comparison function:


bool Comp(const int &a,const int &b)
{
return a>b;
}

A call: sort(vec.begin(),vec.end(),Comp) , so it sort in descending order.

conclusion


Related articles: