Function push() and pop()

Push() - It should store the element at the current position in the embedded array. Increment the current position afterwards. There is no need for checking the current index because the array will throw an exception when the stack is full. Make sure the current index is not changed when the Array class threw an exception.
what should do in other words how I understand this :

Assume there is array of Point name arr1
(2,2) with index 0
(4,4) with index 1
(6,6) with index 2
(8,8) with index 3

if I call push then for element with index 2
arr1.push(2)
then

(2,2) with index 0
(4,4) with index 1
(8,8) with index 2 // index down
(6,6) with index 3 // index up

Pop() - function that decrements the current position and then returns the element at that position. Make sure the current index is not changed when the Array class throws an exception.

As far as I'm understand, Pop() should be the same action but in other direction. However I really not understand enough Is it makes big difference if function store or store not "element in current position" ???
I'm guessing that you're talking about std::queue::push() and std::queue::pop().

References here:
http://cplusplus.com/reference/stl/queue/push/
http://cplusplus.com/reference/stl/queue/pop/

push() inserts an object at the end of the queue and pop deletes the first object in the queue. That's all that they do. Here's an example of their use:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <queue>

int main()
{
  std::queue<int> arr1;
  
  for (int i = 0; i < 5; ++i) arr1.push(i); 
  
  arr1.push(5);
  arr1.pop();
  arr1.push(6);
  arr1.pop();
  
  return 0;
}




arr1 contains:

0 1 2 3 4

0 1 2 3 4 5
1 2 3 4 5
1 2 3 4 5 6
2 3 4 5 6


Of course it doesn't have to be an int. You have a class called Point. I assume it looks like this:
1
2
3
4
5
6
class Point 
{
  int x; int y;
public:
  Point(int _x, int _y) : x(_x), y(_y) {}
};


To use push and pop in this case do this:
1
2
3
4
5
std::queue<Point> arr1;

arr1.push( Point(2,2) ); // makes an object with that constructor and sticks it in the queue.
arr1.push( Point(4,4) );
arr1.pop(); // note pop doesn't have any arguments.  It doesn't create anything. 


Edit: If you want to add objects at the start OR end of a container, try using the deque type instead:
http://cplusplus.com/reference/stl/deque/

This has the following functions:
push_back() - adds an element at the end
push_front() - adds and element at the front
pop_back() - removes the element at the end
pop_front() - removes the element at the front.
Last edited on
Topic archived. No new replies allowed.