简体   繁体   中英

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 (eg 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?

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM