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

标签 c++ stl

通常,您有一个类似 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/

相关文章:

c++ - 我可以使用 std::string* argv 作为主函数参数吗?

java - 将 C++ 内存排序映射到 Java

c++ - 如何保持指针在 vector 中有效,指向其他 vector 中的项目

c++ - 没有优化的清零内存

c++ - STL:在没有额外容器的情况下将函数应用于 adjacent_difference 的结果

c++ - 如何将 std::generate/generate_n 与多态函数对象一起使用?

c++ - 获取所有大于某个值的 STL vector 元素

c++ - 在 Release 模式下访问时 vector 大小为 0

c++ - 具有 2 个值的 STL 映射

c++ - 如何打印数组的所有连续子数组