Originally Posted by
Programmer_P
Who's using maps wrongly?
It was an example, and an example alone. I was really only trying to demonstrate other possible ways of getting mapped values and key values than those already provided, my point being that I thought the current methods kind of sucked.
You, if you truly intend to use a map like that. Saying that the current methods "kind of sucked" is bogus when the map is simply not designed to do that. You are using the wrong container for the job, then blaming the container. That sucks, on your part.
Maps and multimaps are not designed for efficient access by sequential index. They are associative containers designed for efficient access by key value. They are not designed for efficient access by mapped value.
Originally Posted by
Programmer_P
Show the code then...
For example:
Code:
template<typename IT, typename T>
bool value_exists(IT begin, IT end, const T& value)
{
for (; begin != end; ++begin)
{
if (begin->second == value)
{
return true;
}
}
return false;
}
#include <map>
#include <string>
int main()
{
std::map<std::string, int> x;
// ...
if (value_exists(x.begin(), x.end(), 123))
{
// ...
}
}
That said, instead of implementing an algorithm, I could have implemented a predicate and used std::find_if, e.g.,
Code:
template<typename Pair>
class CompareSecond
{
public:
explicit CompareSecond(const typename Pair::second_type& x) : x_(x) {}
bool operator()(const Pair& y) const
{
return y.second == x_;
}
private:
typename Pair::second_type x_;
};
#include <algorithm>
template<typename IT, typename T>
bool value_exists(IT begin, IT end, const T& value)
{
return std::find_if(begin, end,
CompareSecond<typename IT::value_type>(value)) != end;
}
#include <map>
#include <string>
int main()
{
std::map<std::string, int> x;
// ...
if (value_exists(x.begin(), x.end(), 123))
{
// ...
}
}