分页: 1 / 1

stl中的函数对象的问题,求解!!!

发表于 : 2008-03-25 10:58
nick811125
#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的新手
求解!!!!!!
谢谢!!!!!

发表于 : 2008-03-28 19:37
Leo.C
for_each(c.begin(), c.end(), check_unary());
是不是这一行有问题,你可一修改一下修改成
for_each(c.begin(), c.end(), check_unary()());
^^^^^^^^^^^^^^^^^^^
看看对不对。

Re: stl中的函数对象的问题,求解!!!

发表于 : 2008-03-29 10:58
tipfoo
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&
函数check_unary:perator()需要一个整形的引用或指针(可写的),但你给它的是常量指针const int&(不可写的),当然不匹配了。
你可以把

代码: 全选

void operator()(int& i){
改成

代码: 全选

void operator()(int i){
编译就通过了,不过不是你要的结果。set的iterator是不可修改的,另想办法吧。

发表于 : 2008-03-29 11:22
tipfoo
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;
}