我喜欢KeithB的解决方案与免费功能。但是,更可重用的解决方案可能会更好。
什么访问的第一或第二,你可以命名实例任何你喜欢的函数对象:
#include <map>
#include <string>
#include <iostream>
struct GetFirst
{
template <class First, class Second>
First& operator()(std::pair<First, Second>& p)
{
return p.first;
}
template <class First, class Second>
const First& operator()(const std::pair<First, Second>& p)
{
return p.first;
}
};
struct GetSecond
{
template <class First, class Second>
Second& operator()(std::pair<First, Second>& p)
{
return p.second;
}
template <class First, class Second>
const Second& operator()(const std::pair<First, Second>& p)
{
return p.second;
}
};
int main()
{
typedef std::map<std::string, int> Map;
Map persons;
persons["John"] = 20;
persons["Mary"] = 24;
//create named accessors
GetFirst name;
GetSecond age;
for (Map::iterator it = persons.begin(); it != persons.end(); ++it) {
std::cout << name(*it) << " is aging.\n";
++age(*it);
}
for (Map::const_iterator it = persons.begin(); it != persons.end(); ++it) {
std::cout << "Name: " << name(*it) << ", age: " << age(*it) << '\n';
}
}
这是我能做到的最好。我也尝试让这些函子直接接受迭代器,但这样或那样的这意味着该签名将包含依赖名称,这显然使模板类型推演不可能(我无法找到一种方法来重载GetSecond的iterator/const_iterator
即使延迟返回类型的C++ 0x)。
好玩:目前似乎有很多与图形相关的问题:http://stackoverflow.com/questions/1499878/use-a-graph-library-node-network-library-or-roll-my-自己,http://stackoverflow.com/questions/1499217/boost-graph-as-basis-for-a-simple-dag-graph – 2009-09-30 19:17:02
为什么你不能使用提升? – 2009-10-02 18:58:34