基于循环的嵌套范围
Nested range-based for-loops
使用基于范围的for
-循环(C++11),我有以下代码:
vector<atom> protein;
...
for(atom &atom1 : protein) {
...
for(atom &atom2 : protein) {
if(&atom1 != &atom2) {
...
}
}
}
有没有更好/更干净/更快的方法来编写这种嵌套循环?难道没有办法在第二个循环中包含if
条件吗?
类似于ronag的答案是一个更通用的版本:
template<typename C, typename Op>
void each_unique_pair(C& container, Op fun)
{
for(auto it = container.begin(); it != container.end() - 1; ++it)
{
for(auto it2 = std::next(it); it2 != container.end(); ++it2)
{
fun(*it, *it2);
fun(*it2, *it);
}
}
}
更新
template<typename C, typename O1, typename O2>
void each_value_and_pair(C& container, O1 val_fun, O2 pair_fun)
{
auto it = std::begin(container);
auto end = std::end(container);
if(it == end)
return;
for(; it != std::prev(end); ++it)
{
val_fun(*it);
for(auto it2 = std::next(it); it2 != end; ++it2)
{
pair_fun(*it2, *it);
pair_fun(*it, *it2);
}
}
}
它是这样使用的:
main()
{
std::vector<char> values;
// populate values
// ....
each_value_and_pair(values,
[](char c1) { std::cout << "value: " << c1 << std::endl;},
[](char c1, char c2){std::cout << "pair: " << c1 << "-" << c2 << std::endl;});
}
悲伤但真实。使用迭代器和auto关键字的普通循环怎么样?
我想这可能就是您想要的:
for(auto it1 = std::begin(protein1); it1 != std::end(protein); ++it1)
{
for(auto it2 = std::next(it1); it2 != std::end(protein); ++it2)
{
auto& atom1 = *it1;
auto& atom2 = *it2;
// ...
}
}
您的方法很好。如果你想保存if语句,你可以
vector<atom> protein;
int i, j;
...
for(i = 0; i < protein.size() : i++) {
atom &atom1 = protein.at(i);
for(j = i+1; j < protein.size() ; j++) {
atom &atom2 = protein.at(j);
// Do something
// Swap the atom2 and atom1
// Do something again
}
}
相关文章:
- 给定一个C++嵌套的私有结构类型,是否有从文件范围静态函数访问它的策略
- 迭代嵌套映射与范围为循环:没有名为"first"的成员
- 实现编译检查以避免C++嵌套范围
- 矢量下标超出范围,带有嵌套的 for 循环
- 在嵌套名称空间范围中使用名称空间的正确方法
- 带有类的嵌套结构.范围错误
- C++嵌套范围访问
- 局部性得到改进时嵌套的 for 循环的范围 (C++)
- 语句的嵌套范围是否严格合法
- 嵌套c++11范围循环,用于查找组合
- 使用嵌套的std::array创建多维数组,直到运行时才知道维度或范围
- 如何让代码存在于两个或多个非嵌套命名空间的范围内
- C++ 中嵌套增强型 for 循环的范围
- 增强嵌套类的 Python 包装器 - 恢复全局范围
- C++中嵌套函数声明的范围
- 为什么要在嵌套的基于范围的 for 循环中引用
- 基于循环的嵌套范围
- 在基于嵌套范围的 for 循环中使用 auto(用于迭代)
- 对嵌套范围中经常重复出现的变量类型使用相同的名称
- 声明在嵌套范围内初始化的未初始化变量