这两个矢量初始化是否实现相同的结果

Do these two vector initializations accomplish the same result?

本文关键字:实现 是否 结果 初始化 两个      更新时间:2023-10-16

这些是否有效地在做同样的事情?

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和其他人的建议),你仍然有一种方法使用初始值设定项列表,另一种方法是在构造函数的主体中填充向量。

第二个将产生一个向量,其内容在构造函数体的开头有效。

尽管这两种方法都将以相同大小和内容的向量结束,但第二种方法更可取,因为:

  1. 它更干净
  2. 它可能也更快