这篇文章的评论部分中有一个关于使用std::vector::reserve()vs.的帖子std::vector::resize().
这是原始代码:
void MyClass::my_method()
{
my_member.reserve(n_dim);
for(int k = 0 ; k < n_dim ; k++ )
my_member[k] = k ;
}
Run Code Online (Sandbox Code Playgroud)
我相信要写出元素vector,正确的做法是打电话std::vector::resize(),而不是std::vector::reserve().
实际上,以下测试代码在VS2010 SP1的调试版本中"崩溃":
#include <vector>
using namespace std;
int main()
{
vector<int> v;
v.reserve(10);
v[5] = 2;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我是对的,还是我错了?并且VS2010 SP1是对的,还是错了?
我创建了两个向量,用push_back填充另一个向量,另一个用索引填充.我希望这些是平等的,但不是.有人可以解释一下这是为什么吗?
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> v0;
v0.push_back(0);
v0.push_back(1);
v0.push_back(2);
vector<int> v1;
v1.reserve(3);
v1[0] = 0;
v1[1] = 1;
v1[2] = 2;
if (v0 != v1) {
cout << "why aren't they equal?" << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud) 类似问题:
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<vector<int> > vvi;
vvi.resize(1);
vvi[0].reserve(1);
vvi[0][0] = 1;
vector<int> vi = vvi[0];
cout << vi[0]; // cout << vvi[0][0]; works
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这给了我一个段错误,我不知道为什么.