[英]error: no matching function for call to ‘recherche(std::vector >&, std::vector >::iterator, std::vector >::iterator, const char [10])’
我收到此錯誤:錯誤:沒有匹配的 function 調用 'recherche(std::vector >&, std::vector >::iterator, std::vector >::iterator, const char [10])'
錯誤:沒有匹配的 function 調用 'recherche(std::__cxx11::list&, std::__cxx11::list::iterator, std::__cxx11::list::iterator, int)'
錯誤:沒有匹配的 function 調用 'recherche(std::array&, std::array::iterator, std::array::iterator, double)'
#include<iostream>
#include<vector>
#include<array>
#include<list>
#include<algorithm>
#include<iterator>
#include<set>
using namespace std;
template <template<typename> class C, class InputIterator, typename A>
bool recherche(C<A> s, InputIterator debut, InputIterator fin, A n)
{
InputIterator itr;
for (itr = debut; itr != fin; itr++) {
if(*itr == n){
return 1;
}}
return 0;
}
int main(){
vector<string> strVec = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
list<int> my_list = { 12, 5, 10, 9, 4, 90 };
array<float, 5> arr = { 10.56, 20.99, 30.34, 40.12, 10.1 };
cout << recherche(strVec, strVec.begin(), strVec.end(), "Wednesday") << endl;
cout << recherche(my_list, my_list.begin(), my_list.end(), 90) << endl;
cout << recherche(arr, arr.begin(), arr.end(), 30.34) << endl;
return 0;
}
}
std::vector
接受兩個模板參數,一個用於元素,一個用於分配器。 解決此問題的一種方法是在 function 中同時接受它們:
template <template<typename, typename> class C, class InputIterator, typename Elem, typename Alloc>
bool recherche(C<Elem, Alloc> s, InputIterator debut, InputIterator fin, Elem n)
{
InputIterator itr;
for (itr = debut; itr != fin; itr++) {
if(*itr == n){
return 1;
}}
return 0;
}
但是,您也可以通過利用所有 STL 容器實現的value_type
來獲取元素值類型:
template<class Vec, class Elem = Vec::value_type>
void foo(Vec v, Elem e) {
// the element type is extracted in compile time. The only constraint is
// that your container must implement value_type and all stl containers do so
// Of course Vec is not necessarily a vector, it can be a list, an array, an unordered_map etc.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.