-1

Let's say I have a unsigned char buffer that looks like this:

unsigned char buffer = {'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'}

Basically I just want to grab that A's and B's, and pack them into a new buffer like this:

unsigned char buffer2 = {'A', 'B', 'A', 'B', 'A', 'B'  ... etc

is there an efficient way to do this besides looping through every single element? Is there some trick you can do with memcpy or memset?

Thanks!

David G
  • 94,763
  • 41
  • 167
  • 253
Bobby Pardridge
  • 267
  • 6
  • 16
  • 2
    Can you think of a way you can examine each element to see if it is 'A' or 'B' *without* looping at least *once* ?? [copy_if](http://en.cppreference.com/w/cpp/algorithm/copy) will do it if you configure the comparator correctly, but it is still, none-the-less, a loop. (and *neither* of those are valid C++; they're both initializer lists sent to a single scaler var of type `unsigned char`). – WhozCraig Apr 27 '13 at 00:35
  • you mean `buffer[]` and `buffer2[]`, right? – billz Apr 27 '13 at 00:36
  • You want some trick with memcpy that skips every 3rd byte? heh. You'll have to write that yourself. – David Apr 27 '13 at 00:38
  • Yes I meant buffer[] and buffer2[], and I figured it was a hard problem, but I just wanted to make sure incase I was missing something. – Bobby Pardridge May 03 '13 at 16:29

2 Answers2

0

I've never used memcpy, but I would do it like this:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

class Modulo3
{
public:
    Modulo3();
    bool operator()(const char c);
private:
    int num_;
};

Modulo3::Modulo3()
{
    num_ = 0;
}

bool Modulo3::operator()(const char c)
{
    return num_++ % 3 == 0;
}

int main()
{
    string test = "ABCABCABC";

    Modulo3 func;
    remove_if(test.begin(),test.end(),func);

    return 0;
}

The code is the same for vector, list, etc.

lucas92
  • 464
  • 2
  • 11
0

If your data is sorted the way in example you could just loop with incrementing 3 and copying first two of the bytes. Otherwise there is no way you will have to loop on each and every value.

Adnan Akbar
  • 718
  • 6
  • 16