不允许向向量中添加更多元素

Do not allow additon of more elements into a vector

我需要在 std::vector 中保留 x 个元素,比如 10。然后我需要向其中写入一些 y 个值,比如 5(大多数时候 y < x)。有没有办法说明已经写入了多少值以及还有多少值可用?

示例: 假设我分配了 10 个元素

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

但是我只填了其中的7个元素

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

我怎么知道 7 个元素已填充,我还有 3 个可用?

我试过了运行 v.size()v.capacity() 但都是 return 10.

编辑: 我添加了一个使用 std::unique_ptr 的方法。


如果您可以使用 C++17,如何将 v 的元素替换为 std::optional<int>,如下所示?

#include <iostream>
#include <optional>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<std::optional<int>> v(10);

    for (std::size_t i = 0; i<7; ++i){
        v[i] = i;
    }

    std::cout 
        << (v.size() - std::count(v.cbegin(), v.cend(), std::nullopt))
        << " elements have been filled and I still have "
        << std::count(v.cbegin(), v.cend(), std::nullopt) 
        << " available."
        << std::endl << std::endl;

    for(const auto v_i : v)
    {
        if(v_i.has_value()){        
            std::cout << v_i.value() << " ";
        }
    }

    return 0;
}

但如果您受限于旧版本,我认为 std::unique_ptr 将是一个解决方案。 DEMO:

#include <iostream>
#include <memory>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<std::unique_ptr<int>> v(10);

    for (std::size_t i = 0; i<7; ++i){
        v[i] = std::make_unique<int>(i);
    }

    std::cout 
        << (v.size() - std::count(v.cbegin(), v.cend(), nullptr))
        << " elements have been filled and I still have "
        << std::count(v.cbegin(), v.cend(), nullptr) 
        << " available."
        << std::endl << std::endl;

    for(const auto& v_i : v)
    {
        if(v_i){        
            std::cout << *v_i << " ";
        }
    }

    return 0;
}

最后,我找到了类似的方法

你的意思是这样的吗?

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

I need to reserve x number of elements in a std::vector, say 10.

std::vector 有一个 reserve() 方法可以达到这个目的。

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?

向量的 capacity() 是已分配的元素总数,而其 size() 是已分配的已填充元素数。因此,capacity() - size() 是已经分配但未分配的可用元素数。

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

那是因为您正在调用同时分配和填充元素的 vector 构造函数。您正在创建一个名为 vvector,它有 10 个元素填充为 0。这就是为什么 size()capacity() 都是 10。None 的构造函数将做你想做的事。需要使用默认构造函数,然后单独调用reserve(),eg:

std::vector<int> v;
v.reserve(10); // capacity = 10

for (int i = 0; i < 7; ++i)
    v.push_back(i);

size_t filled = v.size(); // size = 7
size_t available = v.capacity() - v.size(); // available = 3