gpt4 book ai didi

c++ - 这个 std::vector 构造函数中发生了什么?

转载 作者:搜寻专家 更新时间:2023-10-31 00:09:24 25 4
gpt4 key购买 nike

我看到一个函数引用了 std::vector,传递给它的参数让我对发生的事情感到困惑。它看起来像这样:

void aFunction(const std::vector<int>& arg) { }


int main()
{
aFunction({ 5, 6, 4 }); // Curly brace initialisation? Converting constructor?

std::vector<int> arr({ 5, 6, 4 }); // Also here, I can't understand which of the constructors it's calling

return 0;
}

谢谢。

最佳答案

对于通过这种结构创建的对象,您需要提供接受 std::initializer_list 的构造函数和 std::vectorone (8) :

vector( std::initializer_list<T> init, 
const Allocator& alloc = Allocator() );

你也可以在那个页面上看到一个例子:

// c++11 initializer list syntax:
std::vector<std::string> words1 {"the", "frogurt", "is", "also", "cursed"};

注意:C++11 也允许用花括号初始化对象:

Someobject {
Someobject( int ){}
};

Someobject obj1(1); // usual way
Someobject obj2{1}; // same thing since C++11

但是你需要小心,如果对象之前提到了 ctor,它将被使用:

std::vector<int> v1( 2 ); // creates vector with 2 ints value 0
std::vector<int> v2{ 2 }; // creates vector with 1 int value 2

注意 2:对于您的问题,列表是如何创建的,在文档中有描述:

A std::initializer_list object is automatically constructed when:

a braced-init-list is used in list-initialization, including function-call list initialization and assignment expressions

a braced-init-list is bound to auto, including in a ranged for loop

关于c++ - 这个 std::vector 构造函数中发生了什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43397425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com