我喜歡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