-2

is a better way to implement this code ?

int getBlockVector(vector<unsigned char>& vect, const int pos, const int length)
  {
    int destinyInt = 0;
    switch (length) {
      case 1 : destinyInt = (0x00 << 24)              | (0x00 << 16)              | (0x00 << 8)             | vecct.at(pos);  break;
      case 2 : destinyInt = (0x00 << 24)              | (0x00 << 16)              | (vect.at(pos + 1) << 8)  | vect.at(pos);  break;
      case 3 : destinyInt = (0x00 << 24)              | (vect.at(pos + 2) << 16)   | (vect.at(pos + 1) << 8)  | vect.at(pos);  break;
      case 4 : destinyInt = (vect.at(pos + 3) << 24)   | (vect.at(pos + 2) << 16)   | (vect.at(pos + 1) << 8)  | vect.at(pos);  break;
      default : destinyInt = -1;
return destinyInt;}

considering the ugly default value. How implement this function with iterators and template for vector, deque, queue, etc.

Note: the bounds are checked before and static_cast is not a desirable option.

kometen
  • 6,536
  • 6
  • 41
  • 51
Holister
  • 13
  • 5

2 Answers2

1

It's better to return an unsigned int, so you'll never get an overflow in case length==4. Also, vect[] is shorter than vect.at(). Finally, you can replace the switch statement by a loop:

unsigned int getBlockVector2(vector<unsigned char>& vect, const int pos, const int length)
{
    unsigned int result = 0;
    for (int k = 0; k < length; ++k)
        result |= vect[k + pos] << (8 * k);
    return result;
}
Adi Levin
  • 5,165
  • 1
  • 17
  • 26
0

Both vector and deque have an at() function, so you can use those two containers with your existing function almost as-is, just declare it as a template:

template <typename CONTAINER_T>
int getBlockVector(CONTAINER_T& vect, const int pos, const int length) {
    int destinyInt = 0;
    switch (length) {
        case 1 : destinyInt = (0x00 << 24)              | (0x00 << 16)              | (0x00 << 8)             | vect.at(pos);  break;
    /*etc...*/
}

A regular queue doesn't support random access or iterators, so you can't really make this function work with a queue. See this thread for workarounds and a more thorough explanation as to why.

You can also initialize destinyInt to -1 when you declare it, so you don't need the default: line in the switch statement, i.e. int destinyInt = -1

Community
  • 1
  • 1
Carlton
  • 4,217
  • 2
  • 24
  • 40