可通过职能模板<代码>auto_iterator_impl<>/code>加以使用。
a. 尽可能少的职能和考虑的工作执行:
template<typename C>
struct auto_iterator_impl
{
C & c;
typename C::iterator it;
auto_iterator_impl(C & c, typename C::iterator & it) : c(c), it(it) {}
operator bool() const { return it != c.end(); }
typename C::iterator operator->() { return it; }
};
template<typename C>
auto_iterator_impl<C> auto_iterator(C & c, typename C::iterator it)
{
return auto_iterator_impl<C>(c, it);
}
试验守则:
void test(std::map<int, int> & m, int key)
{
if (auto x = auto_iterator(m, m.find(key)))
{
std::cout << "found = " << x->second << std::endl;
x->second *= 100; //change it
}
else
std::cout << "not found" << std::endl;
}
int main()
{
std::map<int,int> m;
m[1] = 10;
m[2] = 20;
test(m, 1);
test(m, 3);
test(m, 2);
std::cout <<"print modified values.." <<std::endl;
std::cout << m[1] << std::endl;
std::cout << m[2] << std::endl;
}
产出:
found = 10
not found
found = 20
print modified values..
1000
2000
Online demo : http://www.ideone.com/MnISh