Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ std::vector收缩以适应会使对向量本身的引用无效吗?_C++_Vector - Fatal编程技术网

C++ std::vector收缩以适应会使对向量本身的引用无效吗?

C++ std::vector收缩以适应会使对向量本身的引用无效吗?,c++,vector,C++,Vector,我想知道 std::vector::shrink_to_fit(新容量)将使引用无效 如果发生重新分配,则所有迭代器、指针和引用 与容器相关的内容将无效。否则,不会进行任何更改。“-- 测试代码: #include <vector> #include <iostream> class Test { public: Test(const std::vector<int>& a) : _a(a) {} void print() const

我想知道
std::vector::shrink_to_fit(新容量)
将使引用无效

如果发生重新分配,则所有迭代器、指针和引用 与容器相关的内容将无效。否则,不会进行任何更改。“--

测试代码:

#include <vector>
#include <iostream>
class Test {
public:
    Test(const std::vector<int>& a) : _a(a) {}
    void print() const {
        std::cout << "[";
        for (auto x:_a) std::cout << " " << x;
        std::cout << " ]\n";
    }   
    const std::vector<int>& _a; 
};
int main() {
    std::vector<int> a;
    a.reserve(100);

    for (int i = 0; i < 10; ++i) a.push_back(i);
    Test t(a);
    t.print();
    a.shrink_to_fit();
    t.print(); // will this always work as expected?
}
#包括
#包括
课堂测试{
公众:
测试(const std::vector&a):_a(a){}
void print()常量{

std::cout您所指的段落的意思是,迭代器或对向量大小调整后的元素的引用可能会失效


如果
\u a
是引用,正如您的评论所示,
\u a
将继续是对向量的有效引用,但是
\u a
中的任何迭代器或对元素的引用都将无效。

std::vector::shrink\u to\u fit()
如果发生重新分配,将使引用无效。但与示例代码无关的引用或指向向量所包含数据的指针将无效,而不是指向向量本身的引用:

std::vector<int> v( 10 );
std::vector<int> &vref = v;
int &ref = v[0];
v.resize(2);
v.shrink_to_fit();
// now ref could be invalid, but vref is perfectly fine
std::vectorv(10);
标准:向量&vref=v;
int&ref=v[0];
v、 调整大小(2);
v、 收缩到合适的位置();
//现在ref可能无效,但vref完全可以
如果新的_容量小于旧的_容量(因此向量的容量缩小),引用(测试类的_a属性)是否会无效

否,
测试::_a
在以下情况下不会失效:

a.shrink_to_fit();

如果你有一个
std::vector::iterator
,它将指向
a
的某个元素,那么这样的迭代器将无效。

我的坏…我的意思是
std&\u a;
@rxu编辑以反映这一点。
\u a不是一个引用,而是一个副本,但它是OP中的一个引用example@marcinj在原始版本中根据他的例子,这不是一个参考,但你是正确的,我需要删除这一部分。更好的参考:cpluplus.com充满了错误,所以使用一个好的网站,如Cppreference.com。这两个网站之间的战争似乎会把这个帐户烧成灰烬。哦,好吧。我只是选择了谷歌的最佳结果。@rxu-你可能想要@尼可博拉斯,我希望有一种方法告诉谷歌当我搜索C++ DOCSI时不显示这个站点,我希望是这样的,因为我认为向量是一个指针,指向一个保存数据的实际内存。收缩适合于改变这个指针,但是对向量的引用应该仍然是好的。@ RXU是的