template<class InputIterator, class T> inline
size_t count(
InputIterator First,
InputIterator Last,
const T& Value
)
上面这个是stl中count函数的原型!
哪位大哥写下,怎么实现在一对迭代器中数指定元素出现次数。当然用模板哦!
我写出来的,但是有问题,在dev-cpp中可以运行,在vs2005中报错。
先看看别人怎么写!
谢谢了!
Since you did not post your code, I don't know what you wrote. Here is an example:
[CODE]#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <string>
using namespace std;
// modern trend is to use typename as possible,
// class for typename is a misnomer.
template<typename InputIterator, typename T>
inline size_t count_my( InputIterator First, InputIterator Last, const T& Value )
{
size_t n=0;
while(First!=Last)
{
if(*First == Value) // this may have problem since not all types have "==" defined
++n;
++First;
}
return n;
}
int main(int argc, char** argv)
{
vector<int> vi;
size_t n;
vi.push_back(1);
vi.push_back(2);
vi.push_back(1);
vi.push_back(3);
n = count_my(vi.begin(), vi.end(), 1);
cout<<n<<endl; // outputs 2
list<string> ls;
ls.push_back("to");
ls.push_back("be");
ls.push_back("or");
ls.push_back("not");
ls.push_back("to");
ls.push_back("be");
n = count_my(ls.begin(), ls.end(), string("to"));
cout<<n<<endl; // outputs 2
return 0;
}[/CODE]
#include<vector>
#include<algorithm>
#include<iostream>
int main()
{
using namespace std;
vector<int>v1;
vector<int>::iterator it;
cout<<"please Enter a number you want to input:"<<endl;
int n,m,val;
cin>>n;
for(int i=0;i<n;i++)
{
cin>>m;
v1.push_back(m);
}
cout<<"v1=(";
for(it=v1.begin();it!=v1.end();it++)
cout<<*it<<" "<<")"<<endl;
cin>>val;
vector<int>::iterator::difference_type result;
result = count(v1.begin(), v1.end(), val);
cout << "The count of val is " << result << endl;
system("pause");
return 0;
}
[此贴子已经被作者于2007-6-12 12:53:26编辑过]
你们的都可以!
这个是我的:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
template<typename tcon,typename tval>
size_t count(typename tcon::iterator fir,typename tcon::iterator sec,
const tval &key){
size_t i = 0;
for (;fir != sec;++fir)
if (*fir == key)
++i;
return i;
}
int main(){
vector<string> svec;
string temp;
while (cin >> temp)
svec.push_back(temp);
size_t i = count(svec.begin(),svec.end(),string("love"));
cout << i << endl;
system("pause");
return 0;
}
你们都把迭代器直接作为类型参数去操作,我觉得是把容器类型作为模板参数,再用typename去指定迭带器,去作为形参。
究竟这个模板参数怎么去选择?我有点迷惑了!你们怎么就不约而同的这样去实现呢?
还有,我这个在dev-cpp里是可以的,但是在2005里不行!
这又是为什么!
我不知道两个编译器如何分析你的代码的,估计vc编译器在分析“类的内部类型相同时(T::iterator)”不会聪明到可以分析出这个T是否对应.由此导致无法根据给定参数确定模板类型参数。
dev可能可以分辨出来。。。