【问题标题】:How do I properly use a range-based for loop for an std::array如何为 std::array 正确使用基于范围的 for 循环
【发布时间】:2021-10-21 15:20:56
【问题描述】:

我可以使用传统的 for 循环和带有迭代器的传统 for 循环来遍历数组,但是当我尝试使用基于范围的 for 循环时,我不会得到相同的结果。

#include <iostream>
#include <array>

int main() {
    std::array<int, 5> ar = {1, 2, 3, 4, 5};
    for(int i = 0; i < 5; i++) {
        std::cout << ar[i] << " ";
    }
    std::cout << std::endl;

    for(std::array<int, 5>::const_iterator it = ar.begin(); it != ar.end(); ++it) {
        std::cout << *it << " ";
    }
    std::cout << std::endl;

    for(const int& i: ar) {
        std::cout << ar[i] << " ";
    }
    std::cout << std::endl;
}
1 2 3 4 5 
1 2 3 4 5 
2 3 4 5 0

【问题讨论】:

    标签: c++ for-loop iterator


    【解决方案1】:

    range-based for loop for(const int&amp; i: ar) 中,i 指的是元素而不是索引。所以

    for(const int& i: ar) {
        std::cout << i << " ";
    }
    

    【讨论】:

    • 这里使用for(const int&amp; i: ... 没有多大意义。 for(int i: ... 更高效(对于原始类型,按值传递比按引用传递更有效,因为它避免了额外的取消引用并且副本成本低)。
    • @PaulSanders 编译器是否优化了这里不必要的引用?
    • @prehistoricpenguin 很可能,是的。但为什么要冒险呢?在这里用引用编码循环只是愚蠢的。
    猜你喜欢
    • 2011-10-21
    • 2016-06-19
    • 1970-01-01
    • 2016-10-31
    • 1970-01-01
    • 2014-01-11
    • 1970-01-01
    相关资源
    最近更新 更多