大佬教程收集整理的这篇文章主要介绍了c – 创建STL映射键迭代器,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
那么你怎么能写一个兼容的类KeyIterator,它包装map并提供对该map中键的标准迭代器访问.
例如:
map<string,X> m= ... KeyIterator<string> ki(m); for(KeyIterator<string>::iterator it=ki.begin();it!=ki.end();++it) cout << *it;
KeyIterator应该是轻量级的,因此您可以从几乎没有开销的方法返回它.
编辑:
我不确定我是否完美解释过,让我给出一个更好的用例(半伪):
class PersonManager { private: map<string,Person> people; public: //this version has to iterate the map,build a new structure and return a copy vector<string> getNamesStandard(); //this version returns a lightweight container which can be iterated //and directly wraps the map,allowing access to the keys KeyIterator<string> getNames(); }; void PrintNames(PersonManager &pm) { KeyIterator<string> names = pm.getNames(); for(KeyIterator<string>::iterator it=names.begin();it!=names.end();++it) cout << *it << endl; }
#include <map> #include <string> #include <iterator> template <class map> class KeyIterator { typename map::const_iterator iter_; public: KeyIterator() {} KeyIterator(typename map::iterator iter) :iter_(iter) {} KeyIterator(typename map::const_iterator iter) :iter_(iter) {} KeyIterator(const KeyIterator& b) :iter_(b.iter_) {} KeyIterator& operator=(const KeyIterator& b) {iter_ = b.iter_; return *this;} KeyIterator& operator++() {++iter_; return *this;} KeyIterator operator++(int) {return KeyIterator(iter_++);} const typename map::key_type& operator*() {return iter_->first;} bool operator==(const KeyIterator& b) {return iter_==b.iter_;} bool operator!=(const KeyIterator& b) {return iter_!=b.iter_;} }; int main() { std::map<std::string,int> m; KeyIterator<std::map<std::string,int> > ki; for(ki=m.begin(); ki!=m.end(); ++ki) cout << *ki; }
http://codepad.org/4wxFGGNV没有比这更轻量级.但是,它需要在地图类型上模板化迭代器,而不是键类型,这意味着如果您试图隐藏内部,则必须提供一些实现细节.
以上是大佬教程为你收集整理的c – 创建STL映射键迭代器全部内容,希望文章能够帮你解决c – 创建STL映射键迭代器所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。