微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

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 类使用 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;
    }
    // ...
};

这里的菜鸟....

解决方法

知道如何在大括号中接受多个参数 [...]

它被称为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)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。