gpt4 book ai didi

c++ - Bitset 作为函数的返回值

转载 作者:搜寻专家 更新时间:2023-10-31 02:20:44 29 4
gpt4 key购买 nike

我想要一个接口(interface),其函数返回一个位集:

class IMyInterface
{
public:
virtual std::bitset<100> GetBits() = 0;
};

问题是我不想强制设置bitset 的大小。所以我想我必须改用 boost::dynamic_bitset:

class IMyInterface
{
public:
virtual boost::dynamic_bitset<> GetBits() = 0;
};

不过我听说 boost::dynamic_bitsetstd::bitset 慢。是否有任何其他方法可以避免使用 dynamic_bitset 并有一个返回 std::bitset 的接口(interface),其大小由实现者确定?

最佳答案

首先,由于其静态性,std::bitset is not considered to be a good solution .除了boost::东西,你可以使用像...

template<size_t N>
class IMyInterface {
public:
virtual std::bitset<N> GetBits() = 0;
};

但那样还是太静态了,不是吗?嗯,the standards specify that there's an specialization of std::vector<bool> ,通常实现为动态的、内存高效的 std::bitset !所以……

#include <vector>

class IMyInterface {
public:
virtual std::vector<bool>& GetBits() = 0;
};

编辑:制作IMyInterface::GetBits()为提高效率返回一个引用。

关于c++ - Bitset 作为函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32293533/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com