C ++ for_each()和对象函数 [英] c++ for_each() and object functions
本文介绍了C ++ for_each()和对象函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的任务如下:
对于给定的整数数组,找到其元素的总和并打印出最终的结果,但要获取总和,您需要在STL中执行for_each()函数仅一次(无循环).
For a given integer array, find the sum of its elements and print out the final result, but to get the sum, you need to execute the function for_each() in STL only once (without a loop).
到目前为止,这是我的代码:
As of now this is my code:
void myFunction (int i) {
cout << " " << i << " " << endl;
}
int main() {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
vector<int> v(array[0], array[10]);
for_each( v.begin(), v.end(), myFunction);
return 0;
}
但是由于某种原因,输出显示为4198853,起初我以为是内存地址,但我发现那是错误的.关于我可能做错了什么?
But for some reason the output shows up as 4198853, at first I thought it was a memory address but I figured out that was wrong. Any idea's as to what I might be doing wrong?
推荐答案
为什么不只是
for_each( array, array+10, myFunction);
我非常确定 int *
可以用作迭代器
I'm quite sure that int*
can be used as iterator
编辑:只需选中此项,它确实可以
EDIT: just checked this, it can indeed
这篇关于C ++ for_each()和对象函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文