【发布时间】:2016-06-26 06:51:59
【问题描述】:
我首先声明string 中的vector,称为test。然后我 push_back string Hello 和 World 并让 a 成为 reference 的 test[0]。然后我 push_back a 到 test。但是,我分别在 push_back 之前和之后打印了a,并观察到a 在推入test 后什么都没有。为什么a 什么都不是?向量在将其元素的reference (a) 推回自身时如何工作?这是否意味着a 不再是reference 的test[0] ?
谢谢。
备注:如果我 push_back test[0] ,a 也变成了无。但是test[0] 仍然是“你好”。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> test;
test.push_back("Hello");
test.push_back("World");
string& a = test[0];
cout << "1"<< a << "\n";
test.push_back(a); //or : test.push_back(test[0]);
cout << "2"<< a << "\n";
}
输出:
1Hello
2
更新:
我明白了,感谢下面的答案和 cmets。我打印了 test 的 size 和 capacity 并观察到它们都是 2 。执行test.push_back(a) 时,向量test 分配新内存并将其旧元素复制到新内存。因此 a ,它的旧元素的引用,变得未定义。
这是使用 reserve 的类似代码。我认为a 变为未定义的原因与我最初的问题相同。 (如果我错了,请告诉我。)
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int main()
{
vector<string> test;
test.push_back("Hello");
test.push_back("World");
string& a = test[0];
cout << "1"<< a << "\n";
cout << "size:" << test.size() << " capacity:" <<test.capacity() <<"\n";
test.reserve(3);
cout << "2"<< a << "\n";
}
输出:
1Hello
size:2 capacity:2
2
【问题讨论】:
-
在
push_back上,所有对向量元素的迭代器、指针和引用都将失效(除了您未测试的某些情况)
标签: c++