A
Andrea Crotti
I often need to check for equality between vectors and I thought that ==
was already defined, but apparently it's not, so I did this
--8<---------------cut here---------------start------------->8---
template <typename X, typename Y>
bool vectorEquals(const vector<X>& first, const vector<Y>& second) {
if (first.size() != second.size())
return false;
for (size_t i=0; i < first.size(); ++i)
if (first != second)
return false;
return true;
}
--8<---------------cut here---------------end--------------->8---
which is pretty standard way to do it I guess, and I should get a
compile time error if the == is not defined for what I want to check,
right?
And the other thing is that I want to be able to "convert" vector of
different types.
Actually I mainly care to do
vector<X> <-> vector<unsigned char>
So I tried this thing::
template <typename INP, typename OUT>
vector<OUT> vectorConversion(const vector<INP>& input) {
size_t size_inp = sizeof(INP);
size_t size_out = sizeof(OUT);
// make sure the sizeof are multiples between them, otherwise it doesn't work!
assert(((size_inp % size_out) == 0) || ((size_out % size_inp) == 0));
vector<OUT> res;
size_t size = (size_inp * input.size()) / size_out;
// I'm sure it's always 1
res.resize(size);
// first convert to network order and then copy brutally
memcpy(&res[0], &input[0], size);
return res;
}
and in one way it works but in the other it doesn't.
vector<int> x = {1,2,3}
// simplifying
convert(convert(x)) = {1, 0, 0}
Any idea?
was already defined, but apparently it's not, so I did this
--8<---------------cut here---------------start------------->8---
template <typename X, typename Y>
bool vectorEquals(const vector<X>& first, const vector<Y>& second) {
if (first.size() != second.size())
return false;
for (size_t i=0; i < first.size(); ++i)
if (first != second)
return false;
return true;
}
--8<---------------cut here---------------end--------------->8---
which is pretty standard way to do it I guess, and I should get a
compile time error if the == is not defined for what I want to check,
right?
And the other thing is that I want to be able to "convert" vector of
different types.
Actually I mainly care to do
vector<X> <-> vector<unsigned char>
So I tried this thing::
template <typename INP, typename OUT>
vector<OUT> vectorConversion(const vector<INP>& input) {
size_t size_inp = sizeof(INP);
size_t size_out = sizeof(OUT);
// make sure the sizeof are multiples between them, otherwise it doesn't work!
assert(((size_inp % size_out) == 0) || ((size_out % size_inp) == 0));
vector<OUT> res;
size_t size = (size_inp * input.size()) / size_out;
// I'm sure it's always 1
res.resize(size);
// first convert to network order and then copy brutally
memcpy(&res[0], &input[0], size);
return res;
}
and in one way it works but in the other it doesn't.
vector<int> x = {1,2,3}
// simplifying
convert(convert(x)) = {1, 0, 0}
Any idea?