这两个矢量初始化是否实现相同的结果
Do these two vector initializations accomplish the same result?
这些是否有效地在做同样的事情?
vector<MyType> stuff;
MyClass(MyType *things, int numThings){
for (int i = 0; i < numThings; ++i){
//stuff[i] = things[i]; //original version of question, fixed
stuff.push_back(things[i]);
}
}
与。
vector<MyType> stuff;
MyClass(MyType *things, int numThings) : stuff(things, things+numThings) {}//fixed
如果是,使用任何一种方法都会增加或减少开销吗?(除了方法1中的额外键入)
否。
第一个方法崩溃,因为它访问的元素超出了零大小向量的末尾。如果通过首先调整向量大小来修复此错误,则向量中的元素将首先初始化,然后使用operator=
覆盖。如果通过在循环中使用push_back()
来修复错误,则可以在循环期间调整向量的大小。
第二种方法在一步中用所需内容初始化向量,这是优选的,因为这更简单且明显正确。它也没有调整向量大小的开销,也没有初始化元素两次的开销。
编辑:看起来第二个也是一个错误:
stuff(things, numThings)
应该是
stuff(things, things + numThings)
我永远记不清标准库类的所有构造函数,很有趣的是string
有这个构造函数,而vector
没有。
固定版本
以下两个版本大致相同:
MyClass(MyType *things, int numThings)
{
stuff.reserve(numThings);
for (int i = 0; i < numThings; i++)
stuff.push_back(things[i]);
}
MyClass(MyType *things, int numThings)
: stuff(things, things + numThings);
{ }
这可能是最好的:
MyClass(MyType*things, int numThings) : stuff(things, things + numThings) {}
// ^^^^^^^^^^^^^^^^^^
取决于相同结果的含义。假设这两种方法都有效(你需要修改第二种方法以匹配Dietrich和其他人的建议),你仍然有一种方法使用初始值设定项列表,另一种方法是在构造函数的主体中填充向量。
第二个将产生一个向量,其内容在构造函数体的开头有效。
尽管这两种方法都将以相同大小和内容的向量结束,但第二种方法更可取,因为:
- 它更干净
- 它可能也更快
相关文章:
- 这个极客对极客的trie实现是否存在内存泄漏问题
- C++方法实现:是否可以避免每次都键入类名?
- 我的堆栈弹出式磁带的实现是否泄漏内存?
- 这C++ AtomicInt 实现是否正确?
- STR这个实现是否安全且可移植?
- 此包络实现是否正确使用 C++11 原子学
- 使用 PIMPL 惯用法,实现是否应始终是类的私有成员?
- 不同平台的 fstream 系列实现是否不同?
- 虚拟 CTOR 的克隆函数实现是否有问题
- fetch_mult的原子实现是否正确?
- 像这样的PIMPL实现是否有任何简单的语法
- 双重检查单例线程的实现是否安全?
- 此并发快速排序实现是否正确?
- C/C 中POW()函数的实现是否随平台或编译器而变化
- std::tuple的实现是否允许在触发空类元素的派生到基转换时失败
- 我的双重检查锁定模式实现是否正确?
- 我的链表实现是否泄漏内存
- std::string 实现是否符合其中 's.c_str() + s.size()' 不一定与 '&s[s.size()]' 相同?
- std::vector 实现是否使用内部数组或链表或其他
- 此访问者实现是否正确