我正在从 Java 切换到 C++,我想知道 C++ 是否包含我在 java 中使用的增强 for 循环,例如:
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
在 C++ 中是否可以使用相同的“快捷方式”?
最佳答案
C++11 可以。它们被称为基于范围的 fors。请记住,您应该将类型限定为引用或对 const 的引用。
C++03 的解决方法是 BOOST_FOR_EACH或 boost::bind结合 std::for_each . Boost.Lambda 可以实现更多奇特的事情。如果您有心情让自己或您的同事感到沮丧,我建议您使用已弃用的绑定(bind)器 std::bind1st
和 std::bind2nd
。
下面是一些示例代码:
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <boost/lambda/lambda.hpp>
#include <functional>
int main()
{
int i = 0;
std::vector<int> v;
std::generate_n(std::back_inserter(v), 10, [&]() {return i++;});
// range-based for
// keep it simple
for(auto a : v)
std::cout << a << " ";
std::cout << std::endl;
// lambda
// i don't like loops
std::for_each(v.begin(), v.end(), [](int x) {
std::cout << x << " ";
});
std::cout << std::endl;
// hardcore
// i know my lib
std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
std::cout << std::endl;
// boost lambda
// this is what google came up with
// using for the placeholder, otherwise this looks weird
using namespace boost::lambda;
std::for_each(v.begin(), v.end(), std::cout << _1 << " ");
std::cout << std::endl;
// fold
// i want to be a haskell programmer
std::accumulate(v.begin(), v.end(), std::ref(std::cout),
[](std::ostream& o, int i) -> std::ostream& { return o << i << " "; });
return 0;
}
关于java - C++ 中增强的 FOR 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8378583/