Hadi GhahremanNezhad
Hadi GhahremanNezhad

Reputation: 2455

How to limit the maximum size of vector?

I am trying to use a limited-size buffer like a queue to put some numbers at the back until it gets to a specific size (e.g. 10) and then remove one element from front when a new element is added to the back.

I have used a vector for this purpose, but after several times of running the program (in debug mode) suddenly, I am getting heap corruption errors like:

Critical error detected c0000374

in the middle of the run, and I think it should be related to memory issues, because the error goes away when I reduce the number of vectors.

So far I just use a vector and put the new value to it each time. For example, suppose the code is like this:

#include <iostream>
using namespace std;

vector<int> myvec;
int i = 0;

int main()
{
    while(True) {
        myvec.push_back(i);
        i++;
    }
    return 0;
}

How can I limit the size of myvec to 10, so that when it contains 10 elements and a new element is being added to it, the first element is removed from the memory?

Is it a good idea to use vectors here, or I should use a queue instead?

Upvotes: 0

Views: 2116

Answers (1)

user11919180
user11919180

Reputation:

You can do something like this->

#include <iostream>
using namespace std;

vector<int> myvec;
int i = 0;

int main()
{
   while(True) {
    if(myvec.size()==10)
    {
        myvec.pop_back();
    }
    myvec.push_back(i);
    i++;
}
return 0;
}

Upvotes: 0

Related Questions