vik*_*raj 32 c++ function vector
在C++中,有没有办法在向量的每个元素上调用一个函数,而不使用遍历所有向量元素的循环?类似于Python中的'map'的东西.
Oli*_*rth 41
是的:std::for_each.
void foo(int a) {
std::cout << a << "\n";
}
std::vector<int> v;
...
std::for_each(v.begin(), v.end(), &foo);
Run Code Online (Sandbox Code Playgroud)
Jer*_*fin 39
你已经提到了几个答案std::for_each.
虽然这些对你提出的问题作出回应,我想补充一点,在我的经验,至少std::for_each是对最标准算法有用.
我使用(例如)std::transform,基本上a[i] = f(b[i]);或者result[i] = f(a[i], b[i]);更频繁地使用std::for_each.许多人经常使用std::for_each打印集合的元素; 为此目的,std::copy与std::ostream_iterator目的地工作更好.
Ind*_*000 18
在C++ 11上:你可以使用lambda.例如:
std::vector<int> nums{3, 4, 2, 9, 15, 267};
std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });
Run Code Online (Sandbox Code Playgroud)
参考:http://en.cppreference.com/w/cpp/algorithm/for_each
用途for_each:
// for_each example
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void myfunction (int i) {
cout << " " << i;
}
struct myclass {
void operator() (int i) {cout << " " << i;}
} myobject;
int main () {
vector<int> myvector;
myvector.push_back(10);
myvector.push_back(20);
myvector.push_back(30);
cout << "myvector contains:";
for_each (myvector.begin(), myvector.end(), myfunction);
// or:
cout << "\nmyvector contains:";
for_each (myvector.begin(), myvector.end(), myobject);
cout << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果你有C++ 11,那么有一个更短的方法:基于范围的.它的目的正是如此.
std::vector<int> v {1,2,3,4,5};
for (int element : v)
std::cout << element; //prints 12345
Run Code Online (Sandbox Code Playgroud)
您也可以在适当的时候将引用和const应用于它,或者在类型很长时使用auto.
std::vector<std::vector<int>> v {{1,2,3},{4,5,6}};
for (const auto &vec : v)
{
for (int element : vec)
cout << element;
cout << '\n';
}
Run Code Online (Sandbox Code Playgroud)
输出:
123
456
Run Code Online (Sandbox Code Playgroud)
OP 提到了mapPython中的函数。
这个 Python 函数实际上将一个函数应用于列表(或可迭代)的每个元素,并返回一个收集所有结果的列表(或可迭代)。
换句话说,它做这样的事情:
def f( x ) :
""" a function that computes something with x"""
# code here
return y
input = [ x1, x2, x3, ... ]
output = map( func, input )
# output is now [ f(x1), f(x2), f(x3), ...]
Run Code Online (Sandbox Code Playgroud)
因此,与 Python 映射最接近的 C++ 标准库实际上是std::transform(来自<algorithm>标题)。
示例用法如下:
#include <vector>
#include <algorithm>
using namespace std;
double f( int x ) {
// a function that computes the square of x divided by 2.0
return x * x / 2.0 ;
}
int main( ) {
vector<int> input{ 1, 5, 10 , 20};
vector<double> output;
output.resize( input.size() ); // unfortunately this is necessary
std::transform( input.begin(), input.end(), output.begin(), f );
// output now contains { f(1), f(5), f(10), f(20) }
// = { 0.5, 12.5, 50.0, 200.0 }
return 0;
}
Run Code Online (Sandbox Code Playgroud)