Re: Best way to pass a map-like container to a function
Am 30.08.2012 22:26, schrieb Marco Guazzone:
When I write a function that expect a container like a vector or a
list as parameter, I usually write a function that accept the
first/last iterator pair (as done by STL):
template <typename It> foo(It first, It last);
But, when the container is a map (or similar), what do you use?
It certainly depends what you want to realize. There are clearly
reasonable use-cases, where the associative container can be considered
as a sequence of elements. This makes sense, because associative
containers and unordered containers also satisfy the Container requirements.
Possibile candidates:
1. Two parameters: the first/last iterator pair:
map<...,...> m;
foo(m.begin(), m.end())
Yes, this is IMO a very intuitive one. But you may need to explain what
foo is going to do, before we speculate on that.
2. Four parameters: the first/last iterator pair representing the
begin/end of keys, and another first/last iterator pair representing
the values:
map<...,...> m;
keys = ...
values = ...
foo(keys.begin(), keys.end(), values.begin(), values.end())
I do'n see much value of this signature, but I certainly think that it
would be nice to have a view on std::map that solely iterates over its
keys or over its values. Java's Map interface provides these views and I
would say that these two views are quite often used.
3. A single parameter: the map
map<...,...> m;
foo(m)
I would consider as a different approach that accepts a range as
argument. Certainly this approach is often very useful as well, for any
container. The very advantage is that the caller has no chance to
provide a wrong combination of iterator arguments.
HTH & Greetings from Bremen,
Daniel Kr?gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]