#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <vector>
using namespace std;
struct Sub : public unary_function<int,void>
{
void operator() (int & ri)
{
ri -= 5;
}
};
int main()
{
int a[10]={0,1,2,3,4,5,6,7,8,9};
copy(a,a+10,ostream_iterator<int>(cout," ");
cout << endl;
for_each(a,a+10,Sub());
copy(a,a+10,ostream_iterator<int>(cout," ");
cout << endl;
return 0
}
以上代码用g++编译通过,豪无问题
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <set>
using namespace std;
struct check_unary: public unary_function<int,void>{
void operator()(int& i){
i -= 5;
}
};
int main(){
set<int> c;
for(int i =0; i < 10; ++i)
c.insert(i);
for(set<int>::const_iterator pos = c.begin(); pos != c.end(); ++pos)
cout<< *pos<<' ';
cout<<endl;
for_each(c.begin(), c.end(), check_unary());
for(set<int>::const_iterator pos = c.begin(); pos != c.end(); ++pos)
cout<< *pos<<' ';
cout<<endl;
return 0;
}
但我将数组换成容器后就编译通不过了
报错为:
myfuc_practice.cpp:41: instantiated from here
/usr/lib/gcc/i486-linux-gnu/4.1.2/../../../../include/c++/4.1.2/bits/stl_algo.h:159:
error: no match for call to ‘(check_unary) (const int&’
myfuc_practice.cpp:27: note: candidates are: void check_unary:perator()(int&
才学stl的新手
求解!!!!!!
谢谢!!!!!
stl中的函数对象的问题,求解!!!
-
- 帖子: 11
- 注册时间: 2008-01-06 19:58
-
- 帖子: 2
- 注册时间: 2007-11-12 18:28
- tipfoo
- 帖子: 303
- 注册时间: 2007-07-12 16:30
- 来自: 桂林
Re: stl中的函数对象的问题,求解!!!
明显少了个分号,还能过,神!nick811125 写了: return 0
}
以上代码用g++编译通过,豪无问题
代码: 全选
error: no match for call to ‘(check_unary) (const int&’
myfuc_practice.cpp:27: note: candidates are: void check_unary:perator()(int&
你可以把
代码: 全选
void operator()(int& i){
代码: 全选
void operator()(int i){
- tipfoo
- 帖子: 303
- 注册时间: 2007-07-12 16:30
- 来自: 桂林
“deque”是相对于数组的一个不错的选择,将set改为deque即可。
代码: 全选
#include <iostream>
#include <iterator>
#include <algorithm>
#include <functional>
#include <deque>
using namespace std;
struct check_unary: public unary_function<int,void>{
void operator()(int& i){
i -= 5;
}
};
int main(){
deque<int> c;
for(int i =0; i < 10; ++i)
c.push_back(i);
for(deque<int>::const_iterator pos = c.begin(); pos != c.end(); ++pos)
cout<< *pos<<' ';
cout<<endl;
for_each(&c[0], &c[10], check_unary());
for(deque<int>::const_iterator pos = c.begin(); pos != c.end(); ++pos)
cout<< *pos<<' ';
cout<<endl;
return 0;
}