在语句中有一个函数for_each
Having a function inside for_each statement
我在尝试在for_each循环中传递函数时不断收到错误消息。我有一个向量,我使用for_each循环遍历该向量中的行,现在我需要一个函数来做某事
示例这就是我想要实现的目标:
void DataPartitioning::doSomething()
{
for_each (label.begin(), label.end(), addToTemporaryVector());
}
void DataPartitioning::addToTemporaryVector()
{
cout<<"sucess";
}
但是我收到一条错误消息说:错误:无效使用void表达式 它们都在同一个类中。
由于它是一个成员函数,因此您需要将其包装在对象上调用它的函子中;大概是调用doSomething
的同一对象:
for_each(label.begin(), label.end(), [this](whatever const &){addToTemporaryVector();});
其中whatever
是容器的值类型。
作为常规的 for 循环可能更清晰:
for (whatever const & thing : label) {
addToTemporaryVector();
}
这假设您没有使用C++11之前的编译器。如果你是,它需要更多的胡言乱语:
for_each(label.begin(), label.end(),
std::bind1st(std::mem_fun(&DataPartitioning::addToTemporaryVector), this));
我不完全确定这是否适用于像你这样不需要参数的函数;但大概你的真实代码确实需要一个参数来对每个元素做一些事情。
您需要使用结构,如下所示:
http://en.cppreference.com/w/cpp/algorithm/for_each
#include <iostream>
#include<string>
#include <vector>
#include <algorithm>
using namespace std;
struct Operation
{
void operator()(string n) { cout<<"success"<<endl; }
};
int main() {
vector<string> vInts(10,"abc");
std::for_each(std::begin(vInts), std::end(vInts), Operation());
// your code goes here
return 0;
}
请注意,运算符的输入必须与向量中的类型相同。(本示例中为字符串,链接中为 int)
addToTemporaryVector
函数不使用this
。因此,您可以将其声明为静态。
此外,它应该将模板类型作为参数label
声明:
static void addToTemporaryVector(const SomeType & item);
然后只需做:
//No parentheses to the function pointer
for_each (label.begin(), label.end(), addToTemporaryVector);
相关文章:
- C++ 中用于二维数组的 for-each 循环
- 计算 fib(n) 的次数称为 FOR EACH n
- 支持自定义 const 本机C++容器类的"for each"
- C++ for-each 语句触发"vector iterators incompatible"断言失败:this->_Getcont() == 0
- 为什么我的矢量中的项目在 C++ 中的 for-each 循环期间不会改变?
- 当循环返回"for each"项的 nullptr 时?
- 正确使用C++ 'for each'选项
- "for each"能保证使用更改数组吗?
- 基于范围的循环与 for-each 循环有何不同
- C++:从"for each"循环中的映射中删除值
- 将函数应用于std::map值,其中包含for each和lambda函数
- 正在擦除for(-each)自动循环中的项目
- g++ 4.4.7 -std=gnu++0x 应该编译"for each"结构吗?
- 将循环转移到C++03 for each
- 在 for-each 循环中使用 'auto' 时是否需要添加'const'?
- C++中的"for each"循环如何知道数组的长度
- 基本c++: for-each循环
- 如何使c++中的for each循环函数与自定义类一起工作
- 如何使用for-each循环来美化析构函数
- for-each 循环生成错误,但 for(it=begin()...在遍历 std::map 包含 unique_ptr 时不会