所以,我正在用C++实现(简化的)-DES,并且我得到了一个有效的扩展器函数。扩展器函数定义为,给定6项输入(例如,{1,2,3,4,5,6} ),我们以以下形式输出新的8项输出:{1,2,4,3,4,3,5,6}。我已经按如下方式实现了这一点,但我相信有一种更好、更快的方法来实现它。有什么建议吗?
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]};
}发布于 2019-03-21 18:17:01
一种更快的方法是避免分配临时向量。如果是vec.capacity() < 8,那么你的代码几乎是最优的。要使其达到最佳状态,请执行以下操作:
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]};
}如果为vec.capacity() >= 8,那么您可能希望避免创建新的向量。为此,您可能希望执行以下操作:
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];
}使用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());
}然后将它们组合在一起:
void expandchars(std::vector<int> &vec){
if (vec.capacity() < 8)
realloc_expandchars(vec);
else
inplace_expandchars(vec);
}https://stackoverflow.com/questions/55277620
复制相似问题