std::set_difference is it possible to compare set and map Keys?

▼魔方 西西 提交于 2020-01-02 14:33:00

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!