问题
So we get a new set of strings, and we have one as map Keys. And we want to do one way
set_difference (note - not set_symmetric_difference). So currently I have such ugly code like:
std::map<std::string, boost::shared_ptr<some_class> > _ds;
std::set<std::string> compare_and_clean(std::set<std::string> &new_)
{
std::set<std::string> result;
std::set<std::string> old;
for (std::map<std::string, std::string>::iterator mi = _ds.begin(); mi != _ds.end(); ++mi)
old.insert(mi->first);
std::set_difference( old.begin(), old.end(), new_.begin(), new_.end(), inserter(result, result.begin()));
for (std::set<std::string>::iterator i = result.begin(); i != result.end(); ++i) {
_ds.erase(*i);
}
return result;
}
I wonder how to do set_difference over map Keys and set in more clean way?
回答1:
Yes: You can iterate over just the keys of the std::map
using a transform iterator.
You can find two implementations of such a transform iterator (one using Boost, the other standalone) in an answer I provided to another question.
来源:https://stackoverflow.com/questions/7758239/stdset-difference-is-it-possible-to-compare-set-and-map-keys