soepblik
soepblik

Reputation: 13

how to add value to a list and move on the other values and remove the last value in c++

I need the following but I don't know exactly which function I need to use for it. I have a vector inputs(2); These inputs are generated again and again The inputs needs to be saved as follows

  1. newest inputs(2)
  2. inputs(2)
  3. inputs(2)
  4. oldest inputs(2)

when a new input is received the oldest input, number four must be deleted from the list and the newest is placed on place 1. Place 2 and 3 are set to place 3 and 4 respectively. I also must be able to read out the older inputs easily.

What is the best way to do this in cpp?

Upvotes: 0

Views: 39

Answers (1)

jrok
jrok

Reputation: 55395

Instead of a vector, use std::deque (a double-ended queue). It lets you push and pop elements from both sides and allows random access to elements.

#include <deque>
#include <iostream>

int main()
{
    std::deque<int> q {4, 3, 2, 1, 0};
    q.push_front(5);
    q.pop_back();
    for (int i : q) std::cout << i << ' ';
    std::cout << "\nmiddle:  " << q[q.size()/2];
}

Upvotes: 1

Related Questions