我有一个名为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";
}
}
我正在尝试不要重复代码,同时仍然担心性能问题。
在函数中,我正在对if (index)
- 循环的每一轮进行for
检查,即使结果总是相同的。
这反对“担心表现”。
我可以通过将检查放在我的for
循环之外来轻松避免这种情况。
但是,我会得到大量重复的代码:
void Drawer::writeVector(...)
{
if (index) {
for (...) {
cout << i << "\t" << vec[i] << "\n";
}
}
else {
for (...) {
cout << vec[i] << "\n";
}
}
}
所以这些对我来说都是“坏”的解决方案。
我一直在想的是两个私有函数,其中一个超出索引,然后调用另一个。
另一个只是超出了价值。
但是,我无法弄清楚如何在我的程序中使用它,我仍然需要if
检查以查看要调用哪一个...
根据问题,多态似乎是一个正确的解决方案。 但我看不出我该怎么用呢。 什么是解决这类问题的首选方法?
这不是一个真正的计划,我只是想学习如何解决这类问题。
答案 0 :(得分:78)
将循环体作为函子传递。它在编译时被内联,没有性能损失。
传递变化的想法在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'; });
}
这段代码并不完美,但你明白了。
在旧的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;
}
同样,代码远非完美,但它给了你一个想法。
答案 1 :(得分:38)
在函数中,我正在对for循环的每一轮进行if(索引)检查,即使结果总是相同的。这反对“担心表现”。
如果确实如此,分支预测器在预测(常量)结果时没有问题。因此,这只会在前几次迭代中导致错误预测的轻微开销。在性能方面无需担心
在这种情况下,为了清晰起见,我主张将测试保留在循环中。
答案 2 :(得分:35)
要扩展Ali的答案,这是完全正确但仍然重复某些代码(循环体的一部分,不幸的是,在使用策略模式时难以避免)......
在这种特殊情况下,代码重复并不多,但有一种方法可以将其减少更多,如果函数体大于几条指令,它就会派上用场。
关键是使用编译器执行常量折叠/死代码消除的能力。我们可以通过手动将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);
}
这样我们最终得到的编译代码相当于你的第二个代码示例(外部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
答案 3 :(得分:0)
在大多数情况下,您的代码已经对性能和可读性有所帮助。一个好的编译器能够检测循环不变性并进行适当的优化。考虑以下与您的代码非常接近的示例:
#include <cstdio>
#include <iterator>
void write_vector(int* begin, int* end, bool print_index = false) {
unsigned index = 0;
for(int* it = begin; it != end; ++it) {
if (print_index) {
std::printf("%d: %d\n", index, *it);
} else {
std::printf("%d\n", *it);
}
++index;
}
}
int my_vector[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
};
int main(int argc, char** argv) {
write_vector(std::begin(my_vector), std::end(my_vector));
}
我正在使用以下命令行对其进行编译:
g++ --version
g++ (GCC) 4.9.1
Copyright (C) 2014 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
g++ -O3 -std=c++11 main.cpp
然后,让我们转储程序集:
objdump -d a.out | c++filt > main.s
write_vector
的结果汇编为:
00000000004005c0 <write_vector(int*, int*, bool)>:
4005c0: 48 39 f7 cmp %rsi,%rdi
4005c3: 41 54 push %r12
4005c5: 49 89 f4 mov %rsi,%r12
4005c8: 55 push %rbp
4005c9: 53 push %rbx
4005ca: 48 89 fb mov %rdi,%rbx
4005cd: 74 25 je 4005f4 <write_vector(int*, int*, bool)+0x34>
4005cf: 84 d2 test %dl,%dl
4005d1: 74 2d je 400600 <write_vector(int*, int*, bool)+0x40>
4005d3: 31 ed xor %ebp,%ebp
4005d5: 0f 1f 00 nopl (%rax)
4005d8: 8b 13 mov (%rbx),%edx
4005da: 89 ee mov %ebp,%esi
4005dc: 31 c0 xor %eax,%eax
4005de: bf a4 06 40 00 mov $0x4006a4,%edi
4005e3: 48 83 c3 04 add $0x4,%rbx
4005e7: 83 c5 01 add $0x1,%ebp
4005ea: e8 81 fe ff ff callq 400470 <printf@plt>
4005ef: 49 39 dc cmp %rbx,%r12
4005f2: 75 e4 jne 4005d8 <write_vector(int*, int*, bool)+0x18>
4005f4: 5b pop %rbx
4005f5: 5d pop %rbp
4005f6: 41 5c pop %r12
4005f8: c3 retq
4005f9: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
400600: 8b 33 mov (%rbx),%esi
400602: 31 c0 xor %eax,%eax
400604: bf a8 06 40 00 mov $0x4006a8,%edi
400609: 48 83 c3 04 add $0x4,%rbx
40060d: e8 5e fe ff ff callq 400470 <printf@plt>
400612: 49 39 dc cmp %rbx,%r12
400615: 75 e9 jne 400600 <write_vector(int*, int*, bool)+0x40>
400617: eb db jmp 4005f4 <write_vector(int*, int*, bool)+0x34>
400619: 0f 1f 80 00 00 00 00 nopl 0x0(%rax)
我们可以看到,在函数开始时,我们检查了该值并跳转到两个可能的循环之一:
4005cf: 84 d2 test %dl,%dl
4005d1: 74 2d je 400600 <write_vector(int*, int*, bool)+0x40>
当然,这只有在编译器能够检测到条件是实际不变的情况下才有效。通常,它非常适合标志和简单的内联函数。但是,如果条件是“复杂的”,请考虑使用其他答案中的方法。