基于循环选择的条件。
if(valid)
for (std::multimap<int,int>::reverse_iterator rit=id_count.rbegin(); mcount<10 && rit!=id_count.rend();++rit)
else
for (std::multimap<int,int>::iterator rit=id_match.begin(); mcount<10 && rit!=id_match.end();++rit)
{
//this is common for both for loop
}
如何在C ++中实现这一目标?
答案 0 :(得分:3)
你别无选择,只能将公共部分放在一个函数中,大致如下:
void somefunction(...)
{
//this is common for both for loops
}
if (valid)
{
for (std::multimap<int,int>::reverse_iterator rit=id_count.rbegin(); mcount<10 && rit!=id_count.rend();++rit)
somefunctiuon(...);
}
else
{
for (std::multimap<int,int>::iterator rit=id_match.begin(); mcount<10 && rit!=id_match.end();++rit)
somefunctiuon(...);
}
答案 1 :(得分:1)
这可以说是最有用的例子,它的 不 值得合并循环逻辑,尽管它确实有效。这里提供了利息价值......
#include <iostream>
#include <map>
int main()
{
std::multimap<int,int> id_count = { {1,2}, {9, -2}, {1,44}, {2,3}, {3,5}, {7,34} };
for (int valid = 0; valid < 2; ++valid)
{
std::cout << "valid " << valid << '\n';
int mcount = 0;
for (std::multimap<int,int>::iterator it = valid ? id_count.rbegin().base()
: id_count.begin();
mcount<10 && (valid ? it--!=id_count.begin() : it!=id_count.end());
(valid ? it : ++it), ++mcount)
{
std::cout << "[mcount " << mcount << "] "
<< it->first << ',' << it->second << '\n';
}
std::cout << '\n';
}
}
答案 2 :(得分:1)
您可以创建模板功能:
#include <map>
#include <iostream>
template<typename I> void func(I begin, I end) {
int mcount = 0;
for (I it = begin; mcount < 10 && it != end; ++it) {
++mcount;
std::cout << "[mcount " << mcount << "] "
<< it->first << ',' << it->second << '\n';
}
}
int main() {
std::multimap<int,int> id_count = { {1,2}, {9, -2}, {1,44}, {2,3}, {3,5}, {7,34} };
for (int valid = 0; valid < 2; ++valid) {
std::cout << "valid " << valid << '\n';
if (valid) {
func(id_count.rbegin(), id_count.rend());
} else {
func(id_count.begin(), id_count.end());
}
std::cout << '\n';
}
}
但是恕我直言这个解决方案有点复杂,所以请考虑其他方法(比如将循环体放在函数中)。
答案 3 :(得分:0)
您可以尝试“#if valid”,例如:
#if 0
for(i=1;i<10;++i)
#else
for(i=2;i<9;++i)
#endif
{
cout << i << endl;
}
答案 4 :(得分:0)
在C ++ 14中,您还可以选择使用通用lambdas:
auto common_code = [/* Capture state if needed */] ( auto& Iter )
{
// Your common code
};
if ( valid )
for ( std::multimap<int, int>::reverse_iterator rit = id_count.rbegin(); mcount < 10 && rit != id_count.rend(); ++rit )
common_code( rit );
else
for ( std::multimap<int, int>::iterator rit = id_match.begin(); mcount < 10 && rit != id_match.end(); ++rit )
common_code( rit );