【发布时间】: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++
我想在 c++ 中做类似在 python 中的操作:
nums=[31, 46, 11, 6, 14, 26]
nlttf=[]
for n in nums:
if n<25:nlttf.append(n)
【问题讨论】:
标签: c++
SomethingIteratable cont;
for (const auto &v : cont) {
// Do something
}
像往常一样,const auto &v 为您提供不可变引用、auto &v 可变引用和auto v 可变深层副本。
注意:您不能在循环中执行任何使您迭代的容器的迭代器无效的操作。
【讨论】:
如果你有 C++11,那么代码如下:
for (int n: iterator) { /*Do stuff with n*/ }
【讨论】:
这是另一个选择,使用 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
【讨论】: