c++ - 对嵌套范围内经常重复出现的变量类型使用相同的名称

标签 c++ for-loop iterator c++11

我经常写这样的东西:

const auto end = some_container.end();
for( auto it = some_container.begin(); it != end; ++it )
{
    const auto &item_container = *it;
    const auto end = item_container.end()
    for( auto it = item_container.begin(); it != end; ++it )
    {
        do_awesome_stuff_with_the_iterator();
    }
}

除了第二个变量的名称endit,到目前为止,我已经给了不同的名称。为子范围内的另一个变量“重用”相同的名称是不好的风格/做法吗?我知道您将无法访问外部 endit 变量,但这不是必需的。我不认为这会造成混淆(奇怪的后缀名在我眼中更难看),但是是否有具体的理由不这样做?

最佳答案

既然你有这个标记的c++0x,你为什么不简单地使用std::foreach() 和一个lambda 函数?

我手边没有可识别 lambda 的编译器,但应该可以这样做:

// Beware, brain-compiled code ahead!
std::foreach( some_container.begin()
            , some_container.end()
            , [](some_element& v) {
              std::foreach( v.begin()
                          , v.end()
                          , [](another_element& u) {
                            do_awesome_stuff_with_the_element(u);
                          }
            }
            );

但是,使用新的基于范围的 for 循环,这可能会变得更具可读性:

// Beware, brain-compiled code ahead!
for (auto& v: some_container)
    for(auto& u : v)
        do_awesome_stuff_with_the_element(u);

关于c++ - 对嵌套范围内经常重复出现的变量类型使用相同的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6389485/

相关文章:

c++11 - unique_ptr 向量的取消引用包装器?

c++ - 使用 std::vector::erase 和 const_iterators

c++ - 新手 : Performance Analysis through the command line

concurrency - 如何打印并发和递归函数的结果?

c++ - 函数返回基类而不是派生类,这是编码错误还是 Visual C++ 错误?

c - Makefile -std=c99 错误

python - 生成器内的 for 循环?

c++ - 什么时候在构造函数和析构函数中调用 this-> 是安全的

c++ - 在不区分大小写的 std::map 中无法将 std::wstring 转换为 LPCTSTR

c++ - 如果我正在使用 `const char*` s,如何使用期望 `std::byte` 的接口(interface)