这篇文章的评论部分中有一个关于使用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是对的,还是错了?
我试图了解以下行为:
#include <vector>
#include <iterator>
struct Foo {
Foo(int a) : a_ {a} {}
const int a_; // Note the const
};
int main(int argc, char **argv) {
std::vector<Foo> v1 {Foo {0}};
std::vector<Foo> v2 {Foo {1}};
auto first = std::begin(v2);
auto last = std::end(v2);
for (; first != last; ++first) {
v1.push_back(*first); // Fine
}
//v1.insert(v1.begin(), first, last); // Does not compile
return 0;
}
Run Code Online (Sandbox Code Playgroud)
事实证明,该const成员Foo隐含地删除了使用Foo的副本赋值运算符std::vector::insert.
为什么std::vector::insert需要在std::vector::push_back复制构造时复制赋值?这是否意味着手动连接两个向量可能更有效?这是使用LLVM.