c++vectorpush-back

Erasing the first entry of a vector, after the maximum is reached


I have a vector in which i save coordinates. I perform a series of calculations on each coordinate, thats why i have a limit for the vector size. Right now i clear the vector, when the limit is reached. I'm searching for a method, that let's me keep the previous values and only erases the very first value in the vector.

Simplified, something like this (if the maximum size of the vector would be 4).

vector<int> vec;
vec = {1,2,3,4}
vec.push_back(5);

vec = {2,3,4,5}

Is this possible?


Solution

  • As suggested by @paddy, you can use std::deque, it is most performant way to keep N elements if you .push_back(...) new (last) element, and .pop_front() first element.

    std::deque gives O(1) complexity for such operations, unlike std::vector which gives O(N) complexity.

    Try it online!

    #include <deque>
    #include <iostream>
    
    int main() {
        std::deque<int> d = {1, 2, 3, 4};
        for (size_t i = 5; i <= 9; ++i) {
            d.push_back(i);
            d.pop_front();
    
            // Print
            for (auto x: d)
                std::cout << x << " ";
            std::cout << std::endl;
        }
    }
    

    Output:

    2 3 4 5 
    3 4 5 6 
    4 5 6 7 
    5 6 7 8 
    6 7 8 9