简体   繁体   中英

array of std::bitset as a return value

I need to write a function to do N different Boolean operators on two std::bitset which in each run program can have different size. so I tried to write a function that do the operation inside and return array of bitset but I don't know how should I define return value?

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

I need return value to be something like bitset[N]

The fact that you want to return a variable sized array suggests using a std::vector .

So I would probably do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM