gpt4 book ai didi

c++ - vector 和指针

转载 作者:搜寻专家 更新时间:2023-10-30 23:53:20 25 4
gpt4 key购买 nike

vector 和指向其元素的指针的主要问题是,只要调用 push_back,它们就会在内存中重新分配,从而使指针无效。

我正在尝试实现后缀特里树,我将数据结构 node 存储在节点 vector 中。我知道对于大小为 n 的字符串,数字 n(n+1)/2 是 trie 中节点数的上限。

代码也是如此

std::string T = "Hello StackOverflow!";
std::vector<Node> nodes;

int n = T.length();
nodes.reserve(n*(n+1)/2);

保证我创建的任何指向 nodes 元素的指针都不会失效?也就是说,这会保证 vector 不会被重新分配吗?


编辑:我已经实现了这个,但在运行时我不断收到以下错误。

terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 0) >= this->size() (which is 0)
Aborted (core dumped)

知道是什么原因造成的吗?

最佳答案

根据标准(N4140):

23.3.6.3 vector capacity
....

void reserve(size_type n);

....
After reserve(), capacity() is greater or equal to the argument of reserve if reallocation happens; and equal to the previous value of capacity() otherwise. Reallocation happens at this point if and only if the current capacity is less than the argument of reserve().

23.3.6.5 vector modifiers
....

void push_back(const T& x);
void push_back(T&& x);

Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid.

关于c++ - vector 和指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41557421/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com