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
类使用 std::allocator
分配内存,但我不知道如何在自定义类中使用它。
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
类中实现。
这意味着您需要如下内容:
#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 )
关于c++ - vector 类如何接受多个参数并从中创建一个数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68506926/