How to write a std :: vector debug check?

I want to write a simple scan over an array. I have std::vector<int> data, and I want to find all the indexes of arrays in which the elements are less than 9 and add them to the result vector. I can write this using a branch:

for (int i = 0; i < data.size(); ++i)
    if (data[i] < 9)
        r.push_back(i);

This gives the correct answer, but I would like to compare it with the unpackable version.

Using the original arrays - and assuming that it datais an int array length- is the number of elements in it, and r- an array of results with a lot of space - I can write something like:

int current_write_point = 0;
for (int i = 0; i < length; ++i){
    r[current_write_point] = i;
    current_write_point += (data[i] < 9);
}

How to get similar behavior using vector for data?

+4
source share
3

:

auto scan_branch(const std::vector<int>& v)
{
  std::vector<int> res;
  int insert_index = 0;
  for(int i = 0; i < v.size(); ++i)
  {
    if (v[i] < 9)
    {
       res.push_back(i);
    } 
  }
  return res;
}

26- . 9, , 9, push_back , . .

auto scan_nobranch(const std::vector<int>& v)
{
  std::vector<int> res;
  res.resize(v.size());

  int insert_index = 0;
  for(int i = 0; i < v.size(); ++i)
  {
    res[insert_index] = i;
    insert_index += v[i] < 9;
  }

  res.resize(insert_index);
  return res;
}

, , , 190- . , . , ( ).

+6
std::copy_if(std::begin(data), std::end(data), std::back_inserter(r));
-1

, :

// Resize the vector so you can index it normally
r.resize(length);

// Do your algorithm like before
int current_write_point = 0;
for (int i = 0; i < length; ++i){
    r[current_write_point] = i;
    current_write_point += (data[i] < 9);
}

// Afterwards, current_write_point can be used to shrink the vector, so
// there are no excess elements not written to
r.resize(current_write_point + 1);

, boolean , .

, 9. -, , , , 0-15 (, , 15). , 8 , 9: -, . , x < 0, x 9, , x < 9:

#include <iostream>

// Use bitwise operations to determine if x is negative
int n(int x) {
    return x & (1 << 31);
}

int main() {
    int current_write_point = 0;
    for (int i = 0; i < length; ++i){
        r[current_write_point] = i;
        current_write_point += n(data[i] - 9);
    }
}
-2

Source: https://habr.com/ru/post/1650368/


All Articles