SO, I'm implementing (Simplified)-DES in C++, and I've got a working Expander function. The expander function is defined as, given a 6 entry input (say, {1,2,3,4,5,6}, we output a new, 8 entry output in the following form: {1,2,4,3,4,3,5,6}. I have this implemented as follows, but I'm sure there is a much better, and likely faster way to implement this. Any suggestions?
void expandchars(std::vector<int> &vec){
std::vector<int> temp=vec;
vec={temp[0],temp[1],temp[3],temp[2],temp[3],temp[2],temp[4],temp[5]};
}
A faster way would be to avoid allocating a temp vector. If vec.capacity() < 8
then your code is almost optimal. To make it optimal:
void realloc_expandchars(std::vector<int> &vec){
// Optimal if vec.capacity() <8, since a reallocation is unavoidable
std::vector<int> temp=std::move(vec);
vec={temp[0],temp[1],temp[3],temp[2],temp[3],temp[2],temp[4],temp[5]};
}
If vec.capacity() >= 8
then you probably want to avoid creating a new vector. For that, you might want to do something like:
void inplace_expandchars(std::vector<int> &vec){
vec.insert(vec.begin() + 4, 2 /*count*/, 0 /* value */);
vec[4] = vec[3];
vec[5] = vec[2];
vec[2] = vec[4];
vec[3] = vec[5];
}
Possibly slightly slower, but more readable would be to use std::array:
void inplace_expandchars(std::vector<int> &vec){
std::array<int, 8> temp = {vec[0], vec[1], vec[3], vec[2], vec[3], vec[2], vec[4], vec[5]};
vec.clear();
vec.insert(vec.begin(), temp.begin(), temp.end());
}
And then combine it all:
void expandchars(std::vector<int> &vec){
if (vec.capacity() < 8)
realloc_expandchars(vec);
else
inplace_expandchars(vec);
}