[英]Declaring a generic iterator
I have the following problem: I need to make a function which takes two iterators and a value and checks if the value is found between the two. 我有以下问题:我需要做一个函数,它带有两个迭代器和一个值,并检查是否在两者之间找到该值。 The catch: I can only have one template parameter which denotes the type of the elements from the iterators and the value.
要注意的是:我只能有一个模板参数,该参数表示迭代器中元素的类型和值。
My try is like this, but doesn't seem to work: 我的尝试是这样的,但似乎不起作用:
template <typename T>
T myFind(iterator<std::bidirectional_iterator_tag,T> begin, iterator<std::bidirectional_iterator_tag, T> end, T elem){
// Code
}
But this doesn't work then: 但这不起作用:
// vector<int> vect; list<string> lst;
myFind(vect.begin(), vect.end(), 15);
myFind(lst.begin(), lst.end(), "some element");
Any ideas? 有任何想法吗? Code after changes:
更改后的代码:
template <typename T>
T myFind(T begin, T end,typename std::iterator_traits<T>::value_type elem){
for(T it = begin; it != end; ++it){
if(*it == elem){
return it;
}
}
return end;
}
Can you have one template parameter that is the iterator type? 可以使用一个模板参数作为迭代器类型吗? If so:
如果是这样的话:
template <typename It>
typename std::iterator_traits<It>::value_type
myFind(It begin, It end, typename std::iterator_traits<It>::value_type elem){
// ...
}
Otherwise, I think your restriction is too strong. 否则,我认为您的限制太强了。
After your edit: If you want to do -
on the iterator that is returned (as you show you do in the comments), you need a random access iterator. 编辑后:如果要执行
-
在返回的迭代器上(如您在注释中所示),您需要一个随机访问迭代器。 However, std::list::iterator
is a bidirectional iterator so you can't. 但是,
std::list::iterator
是双向迭代器,因此您不能这样做。 You will need to use std::prev
(or in C++03, use std::advance ). 您将需要使用
std::prev
(或在C ++ 03中,使用std :: advance )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.