java - C++ 中增强的 FOR 循环

标签 java c++ for-loop

我正在从 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_EACHboost::bind结合 std::for_each . Boost.Lambda 可以实现更多奇特的事情。如果您有心情让自己或您的同事感到沮丧,我建议您使用已弃用的绑定(bind)器 std::bind1ststd::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/

相关文章:

java - 将 url 分配给 Java EE 项目中的 ajax (js) 函数

java - 在java中分割一个包含/的字符串

c++ - Qt:在 child 之前捕获事件

c++ - 在一个简单的 Point 类中,是否有任何关于 getters/setters 而不是公共(public)成员变量的真正论据?

c - C 中的 for 循环异常行为

java - iText 中的复选框字符

java - 我应该把 JDBC 驱动程序放在哪里?

c++ - 在 Windows 和 Linux 之间通过 C++ 套接字发送 float 组

javascript - for 循环中的 If-else 不起作用 - Javascript

list - python 中 if 的单行代码——为什么结果总是列表中的最后一项?