【问题标题】:C++ equivalent to the python code: "for x in iterable:" [duplicate]C ++相当于python代码:“for x in iterable:” [重复]
【发布时间】:2016-05-31 03:56:03
【问题描述】:

我想在 c++ 中做类似在 python 中的操作:

nums=[31, 46, 11, 6, 14, 26]
nlttf=[]
for n in nums:
    if n<25:nlttf.append(n)

【问题讨论】:

标签: c++


【解决方案1】:

那就是Range-based for loop:

SomethingIteratable cont;

for (const auto &v : cont) {
    // Do something
}

像往常一样,const auto &amp;v 为您提供不可变引用、auto &amp;v 可变引用和auto v 可变深层副本。

注意:您不能在循环中执行任何使您迭代的容器的迭代器无效的操作。

【讨论】:

    【解决方案2】:

    如果你有 C++11,那么代码如下:

    for (int n: iterator) { /*Do stuff with n*/ }
    

    【讨论】:

      【解决方案3】:

      如果你有 C++11 或更高版本,那么你可以这样做。

      #include <iostream>
      #include <vector>
      using namespace std;
      
      int main() {
          int num[] = {31, 46, 11, 6, 14, 26};
          vector<int>nlttf;
          for(int n:num){
              if(n<25)nlttf.push_back(n);
          }
          return 0;
      }
      

      阅读 this 基于范围的 for 语句 (C++)。

      对于std::vector,请参阅thisthis 链接。

      【讨论】:

        【解决方案4】:

        这是另一个选择,使用 C++11 和 boost 库:

        #include <iostream>
        #include <boost/foreach.hpp>
        #include <vector>
        int main(){
          std::vector<int> nums {31, 46, 11, 6, 14, 26};
          std::vector<int> nltff;
          BOOST_FOREACH(auto n, nums) if (n < 25) nltff.push_back(n);
          BOOST_FOREACH(auto n, nltff) std::cout << n << " ";
          std::cout << std::endl;
          return 0;
        }
        

        输出:

        11 6 14 
        

        【讨论】:

          猜你喜欢
          • 2021-04-08
          • 1970-01-01
          • 1970-01-01
          • 2011-06-27
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多