简体   繁体   English

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

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

I would like to write to internal array of vector.我想写入内部向量数组。 I could write using data() if vector is initialised.如果向量已初始化,我可以使用data()写入。
However if the vector is empty (but having enough storage), I am not able to write directly to internal array of vector.但是,如果向量为空(但有足够的存储空间),我将无法直接写入向量的内部数组。

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

Output:输出:

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

How to avoid this kind of situations, is it possible to validate data() pointer of vector?如何避免这种情况,是否可以验证向量的data()指针?

Edit:编辑:
I assumed two things with this question, on an empty vector v;我在这个问题上假设了两件事,在一个空vector v; , ,

  • v.reserve(10) allocates memory for 10 elements and v.reserve(10)为 10 个元素分配内存,并且
  • v.data() points to that allocated memory. v.data()指向分配的内存。

You want to use resize , not reserve , and size instead of capacity .您想使用resize而不是reservesize而不是capacity reserve simply gives the vector the added capacity, without actually increasing the size. reserve只是简单地为向量增加了容量,而实际上并没有增加大小。 resize increases the size to match the reserved capacity. resize增加大小以匹配保留容量。

There's no need to concern yourself with how much memory you need to reserve beforehand.您无需担心需要预先保留多少内存。 If performance is not really an issue, you may consider instead using auto-resizable back inserting iterators to push the elements at the step you want to push them.如果性能不是真正的问题,您可以考虑使用自动调整大小的反向插入迭代器在您想要推送它们的步骤推送元素。

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

You need to understand the concept of size and capacity of a vector.您需要了解向量的sizecapacity的概念。 size is the number of elements stored while capacity is internal space allocated. size 是存储的元素数,而容量是分配的内部空间。 capacity is always great than or equal to size.容量总是大于或等于大小。 If you insert elements into the vector and caused the vector to run out of capacity, it will automatically increase its capacity by allocating a new space twice of current capacity, then copy existing elements into the new space, then delete the old space.如果在vector中插入元素导致vector容量不足,它会自动通过分配两倍当前容量的新空间来增加容量,然后将现有元素复制到新空间中,然后删除旧空间。

If you are planning to insert a large number of elements into a vector, the "auto increasing capacity" feature is not efficient, as it will keep allocating new spaces and copying elements.如果您计划将大量元素插入向量中,“自动增加容量”功能效率不高,因为它会不断分配新空间并复制元素。 Instead, you can use reserve() to allocate enough space beforehand, and thus to avoid the process to keep allocating new spaces.相反,您可以使用reserve()预先分配足够的空间,从而避免继续分配新空间的过程。

capacity(): Returns the number of elements that the container has currently allocated space for. capacity():返回容器当前为其分配空间的元素数。

reserve(): Increase the capacity of the vector to the given size or more. reserve():将向量的容量增加到给定的大小或更多。

size(): Returns the number of elements in the container. size():返回容器中元素的数量。

resize(): Changes the number of elements stored. resize():更改存储的元素数量。


Back to your question, you can simply replace reserve with 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;
}


Or, you can insert into the vector directly:或者,您可以直接插入向量:

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

You cannot assign to an element that does not exist.您不能分配给不存在的元素。 Allocating memory is not sufficient, but your code is fine when you resize the vector (or create it with sufficient elements):分配内存是不够的,但是当您调整向量大小(或使用足够的元素创建它)时,您的代码很好:

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

Note that your code is not very idomatic.请注意,您的代码不是很惯用。 I assume you have reasons for that, but passing iterators to write_seq would be much more natural.我假设您有这样做的原因,但是将迭代器传递给write_seq会更自然。

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

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