[英]Declare a function accepting generic iterator
Given this code, is it possible to change dumpStrings()
to be able to iterate over any container of string
, like say a list<string>
? 鉴于此代码,是否可以更改dumpStrings()
以能够遍历任何string
容器,例如list<string>
?
#include <vector>
#include <string>
#include <ostream>
#include <iostream>
using namespace std;
void dumpStrings(vector<string>::iterator it, vector<string>::iterator end)
{
while (it != end) {
cout << *it++ << endl;
}
}
int main()
{
vector<string> strVector;
strVector.push_back("Hello");
strVector.push_back("World");
dumpStrings(strVector.begin(), strVector.end());
return 0;
}
Create a template 创建一个模板
template<class iterator_type>
void dumpStrings(iterator_type it, iterator_type end)
{
while (it != end) {
cout << *(it++) << endl;
}
}
The template also removes the limit of the container value type to string. 该模板还将容器值类型的限制删除为字符串。 Note that you need the parentheses around the it++. 请注意,您需要围绕它的括号++。
yes 是
http://www.boost.org/doc/libs/1_45_0/libs/utility/enable_if.html http://www.boost.org/doc/libs/1_45_0/libs/utility/enable_if.html
http://www.cplusplus.com/reference/std/iterator/iterator_traits/ http://www.cplusplus.com/reference/std/iterator/iterator_traits/
http://www.boost.org/doc/libs/1_44_0/libs/type_traits/doc/html/boost_typetraits/reference/is_same.html http://www.boost.org/doc/libs/1_44_0/libs/type_traits/doc/html/boost_typetraits/reference/is_same.html
template<class I>
typename enable_if<
is_same<typename iterator_traits<I>::value_type, string>
>::type
function(...
I don't think there's anything as simple as you'd like. 我不认为有什么比你想要的简单。 Ideally, you could just do something like 理想情况下,你可以做一些类似的事情
void dumpStrings(AbstractIterator<string> beg, AbstractIterator<string> end) { }
but the STL iterators don't seem to have any inheritance hierarchy, irritatingly enough. 但是STL迭代器似乎没有任何继承层次结构,令人恼火。 So it looks like you're stuck with using function templates - that's how it's done in the STL Algorithms Library . 所以看起来你仍然坚持使用函数模板 - 这就是在STL算法库中完成的 。
Sorry - I wish there was a better way, too, but this'll have to do. 对不起 - 我希望有一个更好的方法,但这必须要做。 Just remember to declare the full function template in the header file! 只记得在头文件中声明完整的函数模板!
Please try this, this would work in all container: 请试试这个,这适用于所有容器:
template<class T>
void disp(T &t)
{
for( auto itr=t.begin();itr!=t.end();itr++)
cout<<*itr<<endl;
}
.cpp
vector<int> v(3,77);
list<string> l(5,"Hello");
disp(l)
disp(v);
Note: Don't forget to include< string >, 注意:不要忘记包含< string >,
And auto is available in c++ 11 而auto在c ++ 11中可用
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.