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
Any idea how to do accept multiple arguments in curly braces and form an array?
std::vector
class uses std::allocator
to allocate memory, but I do not know how to use this in a custom 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;
}
// ...
};
noob here ....
Any idea how to do accept multiple arguments in curly braces [...]
It is called list initialization.
You need to write a constructor which accepts the std::initilizer_list
(as @Retired Ninja mentioned in the comments) as argument, so-that it can be achieved in your MinHeap
class.
That means you need something like as follows:
#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 << " ";
}