首页 > 解决方案 > Do not allow additon of more elements into a vector

问题描述

I need to reserve x number of elements in a std::vector, say 10. Then I need to write some y number of values into it, say 5 (most of the time y < x). Is there a way to say how many values have been written to it and how may are still available?

Example: Say I allocate 10 elements

std::vector<int> v(10);

But I only fill 7 of these elements

for (unsigned i = 0; i<7; i++)
  v[i] = i;

How can I tell that 7 elements have been filled and I still have 3 available?

I tried running v.size() and v.capacity() but both return 10.

标签: c++stlc++14stdvector

解决方案


你的意思是这样的吗?

std::vector<int> a; // dont allocate anything

// allocate memory for 10 elements, 
// but dont actually create them. a.size() is still 0.
a.reserve(10); 

for(std::size_t i = 0; i < 7; ++i) {
    // copy i to a new element at the back 
    // of the vector. This will never reallocate 
    // memory, as long as at most 10 elements 
    // are pushed:
    a.push_back(i); 
}
// a.size() is now 7

推荐阅读