我理解为什么这会导致段错误:
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
int iArr[5] = {1, 2, 3, 4, 5};
int *p = iArr;
copy(p, p+5, v.begin());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
但为什么这不会导致段错?
#include <algorithm>
#include <vector>
using namespace std;
int main()
{
vector<int> v;
int iArr[5] = {1, 2, 3, 4, 5};
int *p = iArr;
v.reserve(1);
copy(p, p+5, v.begin());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
两者都是错误的,因为您要复制到空矢量并且复制要求您有空间进行插入.它不会自行调整容器大小.你可能需要的是back_insert_iterator和back_inserter:
copy(p, p+5, back_inserter(v));
Run Code Online (Sandbox Code Playgroud)
这是未定义的行为 - reserve()为至少一个元素分配缓冲区,并且该元素保持未初始化.
所以要么缓冲区足够大,所以你在技术上可以访问第一个之外的元素,或者它不够大,你恰好没有发现任何问题.
底线是 - 不要这样做.仅访问合法存储在vector实例中的元素.