2012-05-03 99 views
0

我需要幫助來定義一個專業map,我無法獲得專業map :: iterator來編譯正確。如何在std :: map類中定義一個迭代器

如何爲find()調用定義此迭代器?

代碼:

// My case-insensitive-less functor, which has historically worked fine for me: 
struct ci_less : std::binary_function<std::string, std::string, bool> 
{ 
    // case-independent (ci) compare_less binary function 
    struct nocase_compare : public std::binary_function<unsigned char,unsigned char,bool> 
    { 
    bool operator() (const unsigned char& c1, const unsigned char& c2) const { 
     return tolower (c1) < tolower (c2); 
    } 
    }; 
    bool operator() (const std::string & s1, const std::string & s2) const { 
    return std::lexicographical_compare (s1.begin(), s1.end(), 
             s2.begin(), s2.end(), 
             nocase_compare()); // comparison 
    } 
}; 

//My offending code: 
template <class T> 
class CaseInsensitiveMap : public map<string, T, ci_less> 
{ 
public: 
// This one actually works, but it requires two "find()" calls. 
// I can't ethically call find twice. 
    const T* lookup(const T& key) const { 
    if (find(key) == map<string, T, ci_less>::end()) return 0; 
    else            return &find(key)->first; 
    } 
// This one complains with errors shown below. 
    T* lookup(const T& key) { 
    CaseInsensitiveMap<T>::iterator itr = find(key); 
    if (itr == map<string, T, ci_less>::end()) return 0; 
    else    return itr->second; 
    } 
}; 

錯誤:

In member function 'T* CaseInsensitiveMap<T>::lookup(const T&)' :
    error: expected ';' before 'itr'
    error: 'itr' was not declared in this scope

+1

我不認爲'std :: map'是爲了繼承而來的。 – chris

+2

將來,請將您的代碼和錯誤內聯發佈,而不是鏈接到外部網站。 – ildjarn

回答

4

typename關鍵字添加到您的變量的類型:

typename CaseInsensitiveMap<T>::iterator itr = find(key); 

無論如何,你不應該繼承STL容器。閱讀爲什麼你不應該這樣做here

編輯:既然你實現所有的情況下insenstitive地圖,就可以實現這種方式,沒有繼承std::map,只需提供自己的比較對象:

#include <iostream> 
#include <map> 
#include <string> 

using namespace std; 

struct nocase_compare { 
    bool operator() (const unsigned char& c1, const unsigned char& c2) const { 
     return tolower (c1) < tolower (c2); 
    } 
}; 

struct map_comparer { 
    bool operator() (const std::string & s1, const std::string & s2) const { 
    return std::lexicographical_compare (s1.begin(), s1.end(), 
             s2.begin(), s2.end(), 
             nocase_compare()); // comparison 
    } 
}; 

template<class T> 
struct CaseInsensitiveMap { 
    typedef std::map<std::string, T, map_comparer> type; 
}; 

int main() { 
    CaseInsensitiveMap<int>::type my_map; 
    my_map["foo"] = 12; 
    std::cout << my_map["FoO"] << "\n"; 
    my_map["FOO"] = 100; 
    std::cout << my_map["fOo"] << "\n"; 
} 

此輸出:

12 
100 
0

typename CaseInsensitiveMap :: iterator itr = find(key);

at line#31