vector class 如何接受多个参数并从中创建一个数组?

How does vector class takes multiple argument and create a array out of it?

vector example

vector<int> a{ 1,3,2 }; // initialize vectors directly  from elements
for (auto example : a)
{
    cout << example << " ";   // print 1 5 46 89
}
MinHeap<int> p{ 1,5,6,8 };    // i want to do the same with my custom class   

知道如何接受花括号中的多个参数并形成数组吗?

std::vector class 使用 std::allocator 分配内存,但我不知道如何在自定义 class 中使用它。 VS Code shows std::allocator

I have done the same but it does not work like that

template<typename T>
class MinHeap
{
    // ...
public:
    MinHeap(size_t size, const allocator<T>& a)
    {
        cout << a.max_size << endl;
    }
    // ...
};

这里是菜鸟....

Any idea how to do accept multiple arguments in curly braces [...]

叫做list initialization。 您需要编写一个构造函数,它接受 std::initilizer_list(如评论中提到的 @Retired Ninja)作为参数,以便它可以在您的 MinHeap class.

这意味着您需要如下内容:

#include <iostream>
#include <vector>
#include <initializer_list> // std::initializer_list

template<typename T> class MinHeap final
{
    std::vector<T> mStorage;

public:
    MinHeap(const std::initializer_list<T> iniList)  // ---> provide this constructor 
        : mStorage{ iniList }
    {}
    // ... other constructors and code!
    
    // optional: to use inside range based for loop 
    auto begin() -> decltype(mStorage.begin()) { return std::begin(mStorage);  }
    auto end()  -> decltype(mStorage.end()) { return std::end(mStorage);  }
};

int main()
{
    MinHeap<int> p{ 1, 5, 6, 8 }; // now you can

    for (const int ele : p)   std::cout << ele << " ";
}

(Live Demo)