简体   繁体   中英

error: no matching function for call to ‘recherche(std::vector >&, std::vector >::iterator, std::vector >::iterator, const char [10])’

i got this error: error: no matching function for call to 'recherche(std::vector >&, std::vector >::iterator, std::vector >::iterator, const char [10])'

error: no matching function for call to 'recherche(std::__cxx11::list&, std::__cxx11::list::iterator, std::__cxx11::list::iterator, int)'

error: no matching function for call to '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 takes two template parameters, one for the element and one for the allocator. One way to solve this would be to accept them both in the 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;
}

However you can also get the element value type by taking advantage of value_type that all STL containers implement:

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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM