-1

I want to do in c++ something like in python would be:

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

4 Answers4

3

That would be the Range-based for loop:

SomethingIteratable cont;

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

As usual, const auto &v gives you immutable references, auto &v mutable references and auto v mutable deep copies.

Beware: You may not do anything in the loop that invalidates iterators of the container you iterate.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
0

If you have C++11 or greater, then you can do it this way.

#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;
}

Read this Range-based for Statement (C++).

For std::vector see this and this link.

Prosen Ghosh
  • 635
  • 7
  • 16
0

If you have C++11 then the code is the following:

for (int n: iterator) { /*Do stuff with n*/ }
Alessandro Mascolo
  • 133
  • 1
  • 3
  • 13
0

Here's another option, using C++11 and the boost libraries:

#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;
}

Output:

11 6 14 
RHertel
  • 23,412
  • 5
  • 38
  • 64