user3429531
user3429531

Reputation: 355

How to repopulate value in vector

I set my vector size to 2 and trying to repopulate the input values after it reaches 2. but I have no idea how should I do it.

e.g

output

a
b

after I type in c it will output

c
b

and after I type d it will output

c
d

-

storeInfo.resize(2);//set the size
storeInfo.push_back(something);//put the value inside vector
//how to repopulate with values within the range after it reaches more than 2?

for(int i = 0; i< storeInfo.size(); i++) {
     cout << storeInfo[i];
}

Upvotes: 0

Views: 126

Answers (3)

Zac Howland
Zac Howland

Reputation: 15872

What you appear to be looking for is a FIFO (first in, first out) structure. std::deque fits that mold (sort of), but would require some custom handling to do exactly what you want.

If you are willing/able to use Boost, it has a circular buffer template.

Alternatively, you could also use std::array if you know the size at compile time (again, it would require some custom handling to act like a ring/circular buffer.

Upvotes: 0

micheal.yxd
micheal.yxd

Reputation: 128

you can change your code to these:

storeInfo.insert(storeInfo.begin(), something);
storeInfo.resize(2);


for(int i = 0; i< 2; i++) {
      cout << storeInfo[i];
}

Upvotes: 0

Buddy
Buddy

Reputation: 11028

storeInfo.resize(2);
int curIdx = 0;

while(1) {
  ... <set val somehow> ...
  storeInfo[curIdx] = val;
  curIdx = (curIdx + 1) % 2;
}

Upvotes: 1

Related Questions