繁体   English   中英

如何验证指向 std 向量内部数组的指针

[英]How to validate pointer to std vector internal array

我想写入内部向量数组。 如果向量已初始化,我可以使用data()写入。
但是,如果向量为空(但有足够的存储空间),我将无法直接写入向量的内部数组。

#include <vector>
#include <iostream>

using namespace std;

void write_seq(int *v, size_t len)
{
    for (int i = 0; i < len; i++)
        v[i] = i;
}

int main(void)
{
    vector<int> v;
    cout << "reserve and write\n";
    v.reserve(10);
    write_seq(v.data(), v.capacity());
    cout << "seq length " << v.size() << "\n";
    return 0;
}

输出:

$ g++ main.cpp && ./a.out 
reserve and write
seq length 0

如何避免这种情况,是否可以验证向量的data()指针?

编辑:
我在这个问题上假设了两件事,在一个空vector v; ,

  • v.reserve(10)为 10 个元素分配内存,并且
  • v.data()指向分配的内存。

您想使用resize而不是reservesize而不是capacity reserve只是简单地为向量增加了容量,而实际上并没有增加大小。 resize增加大小以匹配保留容量。

您无需担心需要预先保留多少内存。 如果性能不是真正的问题,您可以考虑使用自动调整大小的反向插入迭代器在您想要推送它们的步骤推送元素。

#include <vector>
#include <iostream>

template<typename Iterator>
void write_seq(Iterator v) {
    for (int i = 0; i < 10; i++) {
        *v = i;  // actually calls std::vector<>::push_back() internally
        v++;
    }
}

int main(void)
{
    std::vector<int> v;
    std::cout << "just write them data!\n";
    write_seq(std::back_inserter(v));
    std::cout << "seq length " << v.size() << "\n";
    return 0;
}

您需要了解向量的sizecapacity的概念。 size 是存储的元素数,而容量是分配的内部空间。 容量总是大于或等于大小。 如果在vector中插入元素导致vector容量不足,它会自动通过分配两倍当前容量的新空间来增加容量,然后将现有元素复制到新空间中,然后删除旧空间。

如果您计划将大量元素插入向量中,“自动增加容量”功能效率不高,因为它会不断分配新空间并复制元素。 相反,您可以使用reserve()预先分配足够的空间,从而避免继续分配新空间的过程。

capacity():返回容器当前为其分配空间的元素数。

reserve():将向量的容量增加到给定的大小或更多。

size():返回容器中元素的数量。

resize():更改存储的元素数量。


回到你的问题,你可以简单地用resize替换reserve

int main(void)
{
    vector<int> v;
    cout << "reserve and write\n";
    v.resize(10);  // use resize() instead of reserve()
    write_seq(v.data(), v.size());
    cout << "seq length " << v.size() << "\n";
    return 0;
}


或者,您可以直接插入向量:

void write_seq(vector<int>& v, size_t len)
{
    for (int i = 0; i < len; i++)
        v.push_back(i);  // add an element to the vector, this changes the size
}

int main(void)
{
    vector<int> v;
    cout << "reserve and write\n";
    v.reserve(10);  // this does not change size, the vector is still empty
    write_seq(v, v.capacity());
    cout << "seq length " << v.size() << "\n";
    return 0;
}

您不能分配给不存在的元素。 分配内存是不够的,但是当您调整向量大小(或使用足够的元素创建它)时,您的代码很好:

int main(void)
{
    vector<int> v(10);                         // vector with 10 element
    write_seq(v.data(), v.size());             // write to those 10 element
    cout << "seq length " << v.size() << "\n"; // size is (still) 10 
    return 0;
}

请注意,您的代码不是很惯用。 我假设您有这样做的原因,但是将迭代器传递给write_seq会更自然。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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