मुझे मुफ्त कार्यों के साथ कीथबी का समाधान पसंद आया। हालांकि, एक और पुन: प्रयोज्य समाधान अच्छा हो सकता है।
क्या समारोह वस्तुओं है कि पहली या दूसरी का उपयोग, जैसा कि आप नाम कर सकते हैं उदाहरणों कुछ भी आप की तरह के बारे में:
#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';
}
}
यह सबसे अच्छा मैं कर सकता है। मैंने उन मज़ेदारों को सीधे इटरेटर को स्वीकार करने की कोशिश की, लेकिन एक तरफ या दूसरा इसका मतलब है कि हस्ताक्षर में निर्भर नाम होंगे जो स्पष्ट रूप से टेम्पलेट प्रकार की कटौती को असंभव बनाता है (मुझे iterator/const_iterator
के लिए गेटसेकंड को अधिभारित करने का कोई तरीका नहीं मिला, यहां तक कि स्थगित वापसी के साथ भी सी ++ 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 –
आप बूस्ट का उपयोग क्यों नहीं कर सकते? –