Ska*_*One 113 c++ design-patterns for-loop c++11
我有一个叫做类Writer的函数writeVector有这样的函数:
void Drawer::writeVector(vector<T> vec, bool index=true)
{
for (unsigned int i = 0; i < vec.size(); i++) {
if (index) {
cout << i << "\t";
}
cout << vec[i] << "\n";
}
}
Run Code Online (Sandbox Code Playgroud)
我试图不要重复代码,同时仍然担心性能.在函数中,我正在if (index)对我的for-loop的每一轮进行检查,即使结果总是相同的.这反对"担心表现".
我可以通过将检查放在我的for-loop 之外来轻松避免这种情况.但是,我会得到大量重复的代码:
void Drawer::writeVector(...)
{
if (index) {
for (...) {
cout << i << "\t" << vec[i] << "\n";
}
}
else {
for (...) {
cout << vec[i] << "\n";
}
}
}
Run Code Online (Sandbox Code Playgroud)
所以这些对我来说都是"坏"的解决方案.我一直在想的是两个私有函数,其中一个超出索引,然后调用另一个.另一个只是超出了价值.但是,我无法弄清楚如何在我的程序中使用它,我仍然需要if检查以查看要调用哪一个...
根据问题,多态似乎是一个正确的解决方案.但我看不出我该怎么用呢.解决这类问题的首选方法是什么?
这不是一个真正的程序,我只是想学习如何解决这类问题.
Ali*_*Ali 79
作为仿函数传递循环体.它在编译时被内联,没有性能损失.
传递变化的想法在C++标准库中无处不在.它被称为战略模式.
如果您被允许使用C++ 11,您可以执行以下操作:
#include <iostream>
#include <set>
#include <vector>
template <typename Container, typename Functor, typename Index = std::size_t>
void for_each_indexed(const Container& c, Functor f, Index index = 0) {
for (const auto& e : c)
f(index++, e);
}
int main() {
using namespace std;
set<char> s{'b', 'a', 'c'};
// indices starting at 1 instead of 0
for_each_indexed(s, [](size_t i, char e) { cout<<i<<'\t'<<e<<'\n'; }, 1u);
cout << "-----" << endl;
vector<int> v{77, 88, 99};
// without index
for_each_indexed(v, [](size_t , int e) { cout<<e<<'\n'; });
}
Run Code Online (Sandbox Code Playgroud)
这段代码并不完美,但你明白了.
在旧的C++ 98中它看起来像这样:
#include <iostream>
#include <vector>
using namespace std;
struct with_index {
void operator()(ostream& out, vector<int>::size_type i, int e) {
out << i << '\t' << e << '\n';
}
};
struct without_index {
void operator()(ostream& out, vector<int>::size_type i, int e) {
out << e << '\n';
}
};
template <typename Func>
void writeVector(const vector<int>& v, Func f) {
for (vector<int>::size_type i=0; i<v.size(); ++i) {
f(cout, i, v[i]);
}
}
int main() {
vector<int> v;
v.push_back(77);
v.push_back(88);
v.push_back(99);
writeVector(v, with_index());
cout << "-----" << endl;
writeVector(v, without_index());
return 0;
}
Run Code Online (Sandbox Code Playgroud)
同样,代码远非完美,但它给你的想法.
Mar*_*sen 38
在函数中,我正在对for循环的每一轮进行if(索引)检查,即使结果总是相同的.这反对"担心表现".
如果确实如此,分支预测器在预测(常量)结果方面没有问题.因此,这只会在前几次迭代中导致错误预测的轻微开销.在性能方面没什么好担心的
在这种情况下,我主张将测试保持在循环内以便清晰.
sya*_*yam 35
为了扩展阿里的答案,这是完全正确但仍然重复一些代码(循环体的一部分,不幸的是,这在使用策略模式时难以避免)...
在这种特殊情况下,代码重复并不多,但有一种方法可以将其减少更多,如果函数体大于几条指令就会派上用场.
关键是使用编译器执行常量折叠/死代码消除的能力.我们可以通过手动将运行时值映射index到编译时值来实现这一点(当只有有限数量的情况时很容易做到 - 在这种情况下为2)并使用在编译时已知的非类型模板参数-时间:
template<bool index = true>
// ^^^^^^ note: the default value is now part of the template version
// see below to understand why
void writeVector(const vector<int>& vec) {
for (size_t i = 0; i < vec.size(); ++i) {
if (index) { // compile-time constant: this test will always be eliminated
cout << i << "\t"; // this will only be kept if "index" is true
}
cout << vec[i] << "\n";
}
}
void writeVector(const vector<int>& vec, bool index)
// ^^^^^ note: no more default value, otherwise
// it would clash with the template overload
{
if (index) // runtime decision
writeVector<true>(vec);
// ^^^^ map it to a compile-time constant
else
writeVector<false>(vec);
}
Run Code Online (Sandbox Code Playgroud)
这样我们最终得到的编译代码相当于你的第二个代码示例(外部if/内部for),但没有自己复制代码.现在我们可以根据需要制作writeVector复杂的模板版本,总会有一段代码需要维护.
请注意模板版本(以非类型模板参数的形式采用编译时常量)和非模板版本(以运行时变量作为函数参数)是如何重载的.这允许您根据需要选择最相关的版本,在两种情况下都具有相似且易于记忆的语法:
writeVector<true>(vec); // you already know at compile-time which version you want
// no need to go through the non-template runtime dispatching
writeVector(vec, index); // you don't know at compile-time what "index" will be
// so you have to use the non-template runtime dispatching
writeVector(vec); // you can even use your previous syntax using a default argument
// it will call the template overload directly
Run Code Online (Sandbox Code Playgroud)