gpt4 book ai didi

c++ - 创建 STL 映射键迭代器

转载 作者:可可西里 更新时间:2023-11-01 18:36:17 25 4
gpt4 key购买 nike

通常,您有一个类似 map<string,X> 的 map 其中键是映射值的名称,并且您需要一个 API 让消费者看到所有名称......例如填充 GUI 列表框。您可以构建一个 vector 并将其作为 API 调用返回,但这样效率很低。您可以只返回对 map 的引用,但随后也可以访问这些值,而您可能不希望这样。

那么您如何编写一个兼容的类 KeyIterator,它包装映射并提供对该映射中的键的标准迭代器访问。

例如:

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
没有比这更轻的了。但是,它要求迭代器根据 map 类型而不是键类型进行模板化,这意味着如果您试图隐藏内部结构,则必须提供一些实现细节。

关于c++ - 创建 STL 映射键迭代器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7667343/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com