gpt4 book ai didi

c++ - C++11 映射值的迭代器(简单透明)

转载 作者:可可西里 更新时间:2023-11-01 17:39:12 26 4
gpt4 key购买 nike

我正在寻找一种简单的方法来为 map 的值创建迭代器在 C++11 中。

这个方法应该简单和透明:简单是因为它应该很容易实现,而透明是因为客户端不应该知道值来自一个映射,而不是一个集合。

这个问题已经问过好几次了。其中许多问题早于 C++11 并使用了我不想使用的 boost。有些并不简单,这里是 John Ahlgren 的解决方案,http://john-ahlgren.blogspot.com/2013/10/how-to-iterate-over-values-of-stdmap.html ,例如需要一页代码来编写自定义迭代器。

其他的不是透明的,也就是明明可以这样写:

map<string,foo> mymap;
for (auto it=mymap.begin();it!=mymap.end();++it){
Foo val= it->second;
...
}

但是,我不想这样做,因为我不想让客户端必须知道数据表示。

问题如下。

我有一堆用长“键”唯一索引的对象。有时我想操纵这些对象的集合。其他时候我想检索一个给定其键的对象。

我不能直接使用“set”类有几个原因,其中最主要的是它不存储可变实例,并且这些实例必须是可变的(显然,键除外)。

因此,我决定将所有对象存储在一个巨大的全局哈希表中:

map<long,Foo> all_the_objects;

然后我不使用 set<Foo>根本。相反,我使用 set<long>并使用适配器模拟一组 Foo,即,

class SetOfFoo{
private: set<long> theKeys;
public:
void insert(const & Foo);
size_t size() return theKeys.size();
bool is_member(const & Foo)
{return theKeys.find(Foo.key)
!= theKeys.end;}
Foo & insert(const & Foo val){
long key=val.key;
all_the_objects[key]=val;
return all_the_objects[key];
}
...::iterator begin() {???}
}

换句话说,SetOfFoo 类的客户端不知道或不需要知道 SetOfFoo 是作为键集实现的。

我也不能自己在适配器类中创建一个 Vector,因为不能在 C++ 集合中存储引用。

是否真的不可能创建一种简单、透明的方法来遍历 map<> 值?我觉得很难相信,因为这是一个非常普遍的需求,而且在我见过的每一种具有哈希表的语言中,这都是微不足道的。我只是不明白这怎么会这么难。

最佳答案

这很简单。

这是一个极其简单的版本,它最低限度地解决了整数到字符串的映射问题。您可以重写您想要的类型,也可以根据需要将其模板化。

#include <map>
#include <iostream>
#include <iterator>
#include <string>
#include <algorithm>

struct map_value_iterator : public std::map<int, std::string>::const_iterator
{
map_value_iterator(std::map<int, std::string>::const_iterator src)
: std::map<int, std::string>::const_iterator(std::move(src))
{

}

// override the indirection operator
const std::string& operator*() const {
return std::map<int, std::string>::const_iterator::operator*().second;
}
};


using namespace std;


int main()
{
map<int, string> myMap { {1, "Hello" }, { 2, "World" } };

copy(map_value_iterator(begin(myMap)), map_value_iterator(end(myMap)), ostream_iterator<string>(cout , " "));
cout << endl;

return 0;
}

程序输出:

Compiling the source code....
$g++ -std=c++11 main.cpp -o demo -lm -pthread -lgmpxx -lgmp -lreadline 2>&1

Executing the program....
$demo
Hello World

关于c++ - C++11 映射值的迭代器(简单透明),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23605961/

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