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)
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)
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.
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++).
If you have C++11 then the code is the following:
for (int n: iterator) { /*Do stuff with n*/ }
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