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

标签 c++ c++11 stdvector class-template stdinitializerlist

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

菜鸟在这里....

最佳答案

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/

相关文章:

c++ - 如何以更好的性能传递和共享 shared_ptr 所有权?

c++ - C++ 11 future / promise 中没有状态错误

c++ - Visual Studio 2012 c++ 对 std 的智能感知评论可能吗?

c++ - 在类中创建 vector 的 vector (二维数组)- 错误 :C++ requires a type specifier for all declarations

c++ - 将旧 vector 设置为新 vector

c++ - 如何从 boost 多数组中获取最大/最小元素

c++ - 计算线间隔中的点数

C++ Try Catch block 不捕获异常

c++ - 使用 std::transform 构造 std::vector。可以返回未命名的结果吗?

c++ - 动态对象的动态数组