R. F. Luis R. F. Luis - 17 days ago 8
C++ Question

How to use std::search on a std::vector passed by reference?

If I have a function in C++ that gets an

std::vector<unsigned char>
by reference, how can I use
to find a signature?

The code looks like this:

int check (const std::vector<unsigned char>& vect)
std::string signature("<!-- signature -->");
std::string signature2("<!-- another -->");
std::vector<unsigned char>::iterator itr;
unsigned int kind = 0;

itr = std::search(vect.begin(),vect.end(),signature.begin(),signature.end());
if (itr!=vect.end()) kind=1;
if (kind == 0)
itr = std::search(vect.begin(),vect.end(),signature2.begin(),signature2.end());
if (itr!=vect.end()) kind=2;
return kind;

is huge , so copying it works , but is a bad solution.

Why this doesn't compile?


The problem is that you are iterating over a const std::vector<unsigned char>, but you try to assign an iterator from that to a non-const std::vector<unsigned char>::iterator.

A simple fix would be to declare the correct type for itr:

std::vector<unsigned char>::const_iterator itr;

If you're using C++11, I would just use auto instead:

auto itr = std::search(vect.begin(),vect.end(),signature.begin(),signature.end());