[英]How to define an iterator in a std::map class
我需要定義專業map
幫助,但無法獲得專業地圖::: iterator進行編譯。
我如何為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;
}
};
錯誤:
在成員函數
'T* CaseInsensitiveMap<T>::lookup(const T&)'
:
錯誤:預期為';'
在'itr'
之前
錯誤:未在此范圍內聲明'itr'
將typename
關鍵字添加到變量的類型中:
typename CaseInsensitiveMap<T>::iterator itr = find(key);
無論如何,您不應該繼承STL容器。 在此處閱讀有關為什么不應該這樣做的信息 。
編輯 :由於您要實現的是不區分大小寫的映射,您可以以這種方式實現它,而無需繼承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
類型名稱 CaseInsensitiveMap :: iterator itr = find(key);
在第31行
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.