c++ - 作为返回值的 std::bitset 数组

标签 c++ bitset

我需要编写一个函数来对两个 std::bitset 执行 N 个不同的 bool 运算符,这两个 std::bitset 在每个运行程序中可以具有不同的大小。所以我尝试编写一个函数在内部执行操作并返回 bitset 数组,但我不知道应该如何定义返回值?

template<size_t SIZE>
    ....  bitwiseOperator(bitset<SIZE> r_1, bitset<SIZE> r_2, vector<int> fun)
    {
      int  k = 0;
      bitset<SIZE> r_12;
      const int N =   fun.size();
      bitset<SIZE> rs[N];
      for(vector<int>::iterator it = fun.begin(); it != fun.end(); ++it) 
      {
        if (*it == 1)         
        {
                r_12 = r_1 & r_2;
        }
        else if(*it == 2)  
        {
                r_12 = r_1 | r_2;
        }
        else if(*it == 3) 
        {
                r_12 = r_1 ^ r_2;
        }
        rs[k] = r_12;
        k++;
     }
        return rs;
    }

我需要返回值类似于 bitset[N]

最佳答案

您想要返回可变大小的数组这一事实建议使用 std::vector

所以我可能会这样做:

template<size_t SIZE>
std::vector<std::bitset<SIZE> > bitwiseOperator(bitset<SIZE> r_1,
    bitset<SIZE> r_2, vector<int> fun)
{
    int k = 0;
    bitset<SIZE> r_12;

    const int N = fun.size(); // not sizeof(fun); !!!

    std::vector<std::bitset<SIZE> > rs(N); // Variable size suggests std::vector

    for(vector<int>::iterator it = fun.begin(); it != fun.end(); ++it)
    {
        if(*it == 1)
        {
            r_12 = r_1 & r_2;
        }
        else if(*it == 2)
        {
            r_12 = r_1 | r_2;
        }
        else if(*it == 3)
        {
            r_12 = r_1 ^ r_2;
        }
        rs[k] = r_12;
        k++;
    }
    return rs;
}

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

相关文章:

c++ - 为什么 C++ 标准允许 std::max_align_t 和 __STDCPP_DEFAULT_NEW_ALIGNMENT__ 不一致?

java - Java中的或运算(BitSet.class)

c++ - 位集超过 32 位?

c++ - std::bitset 在 cpp 中的工作

为 32 位和 64 位处理器强制对齐的 C++ 安全性

java - 如何在 Java 中以位级精度读写文件

c++ - 在 Visual Studio 2005 中通过 C++ 创建 Microsoft Word 文档

c++ - 在 C++ 中,我可以根据指针类型对元素类型进行类型定义吗?

c++ - 如何在最新的 firefox 中简单地测试 XPCOM 组件?

c++ - GridFS 对 mongocxx(mongodb c++ 驱动程序)的 MD5 支持