在 C++ 向量的每个元素上调用函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10516495/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 14:10:11  来源:igfitidea点击:

Calling a function on every element of a C++ vector

c++functionvector

提问by vikaspraj

In C++, is there a way to call a function on each element of a vector, without using a loop running over all vector elements? Something similar to a 'map' in Python.

在 C++ 中,有没有一种方法可以在向量的每个元素上调用函数,而不使用在所有向量元素上运行的循环?类似于 Python 中的“地图”。

回答by Oliver Charlesworth

Yes: std::for_each.

是:std::for_each

#include <algorithm> //std::for_each

void foo(int a) {
    std::cout << a << "\n";
}

std::vector<int> v;

...

std::for_each(v.begin(), v.end(), &foo);

回答by Jerry Coffin

You've already gotten several answers mentioning std::for_each.

你已经得到了几个提到std::for_each.

While these respond to the question you've asked, I'd add that at least in my experience, std::for_eachis about the leastuseful of the standard algorithms.

虽然这些回答了您提出的问题,但至少根据我的经验,我要补充一点,这std::for_each是标准算法中没用的。

I use (for one example) std::transform, which is basically a[i] = f(b[i]);or result[i] = f(a[i], b[i]);much more frequently than std::for_each. Many people frequently use std::for_eachto print elements of a collection; for that purpose, std::copywith an std::ostream_iteratoras the destination works much better.

我使用(为一个例子)std::transform,它基本上是a[i] = f(b[i]);result[i] = f(a[i], b[i]);更频繁比std::for_each。许多人经常使用std::for_each打印集合的元素;为此,std::copy使用std::ostream_iteratoras 作为目的地效果会更好。

回答by Indy9000

On C++ 11: You could use a lambda. For example:

在 C++ 11 上:您可以使用 lambda。例如:

std::vector<int> nums{3, 4, 2, 9, 15, 267};

std::for_each(nums.begin(), nums.end(), [](int &n){ n++; });

ref: http://en.cppreference.com/w/cpp/algorithm/for_each

参考:http: //en.cppreference.com/w/cpp/algorithm/for_each

回答by Alexander Poluektov

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

回答by chris

If you have C++11, there's an even shorter method: ranged-based for. Its purpose is exactly this.

如果你有 C++11,还有一个更短的方法:基于范围的 for. 它的目的正是如此。

std::vector<int> v {1,2,3,4,5};

for (int element : v)
    std::cout << element; //prints 12345

You can also apply references and const to it as well, when appropriate, or use auto when the type is long.

您也可以在适当的时候对其应用引用和 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';
} 

Output:

输出:

123
456

回答by juanchopanza

You can use std::for_eachwhich takes a pair of iterators and a function or functor.

您可以使用std::for_each,它带有一对迭代器和一个函数或函子。

回答by Mateo

The OP mentions the mapfunction in Python. This function actually applies a function to every element of a list (or iterable) and returns a list (or iterable) that collects all results. In other words, it does something like this:

OP 提到了mapPython中的函数。该函数实际上将一个函数应用于列表(或可迭代)的每个元素,并返回一个收集所有结果的列表(或可迭代)。换句话说,它做这样的事情:

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), ...] 

Hence, the closest C++ standard-library equivalent to Python's map is actually std::transform(from the ` header).

因此,与 Python 映射最接近的 C++ 标准库实际上是std::transform(来自 ` 标头)。

Example usage is as follows:

示例用法如下:

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