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

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)

  • @ dbliss,`for_each()`的实现很可能是一个循环,因为它使用模板,应该没有区别.但是,使用C++ 17,它们可能会引入对您完全透明的并行性,并且最终可能会更快地开始. (2认同)

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::copystd::ostream_iterator目的地工作更好.

  • 这是我正在寻找的答案,`transform`比`for_each`更接近Python的`map`,因为`map`生成一个输出列表,而`for_each`调用一个函数但丢弃输出. (6认同)

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


Ale*_*tov 8

用途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)


chr*_*ris 7

如果你有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)

  • @BadDesign,从技术上讲,输出它是应用一个函数,`operator&lt;&lt;(std::cout, element)`。我这篇文章的主要目标是打开这个语法的 OP(以及任何未来的访问者)。不想循环的原因没有说明,也可能是不想全部输入。`for_each` 中也存在一个循环。第二个例子就是这样——一个例子。它表明您可以使用 or ,这让人们可以随意更改它。此外,谁说您需要可修改元素才能在其上调用函数? (2认同)

Mat*_*teo 6

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)