Shu*_*oni 2 c++ stdvector class-template c++11 stdinitializerlist
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
Run Code Online (Sandbox Code Playgroud)
知道如何在大括号中接受多个参数并形成一个数组吗?
std::vectorclass 用于std::allocator分配内存,但我不知道如何在自定义类中使用它。
VS Code 显示std::allocator
template<typename T>
class MinHeap
{
// ...
public:
MinHeap(size_t size, const allocator<T>& a)
{
cout << a.max_size << endl;
}
// ...
};
Run Code Online (Sandbox Code Playgroud)
菜鸟在这里....
知道如何在大括号中接受多个参数 [...]
这称为列表初始化。您需要编写一个接受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 << " ";
}
Run Code Online (Sandbox Code Playgroud)
(现场演示)
| 归档时间: |
|
| 查看次数: |
136 次 |
| 最近记录: |