Search code examples
c++stlstd-pair

copy_if with map whose value is also a std::pair


I have an input map inMap whose type is map<double, pair<int, double>>.

I am trying to filter this map by means of copy_if like this:

map<double, pair<int, double>> outMap;
copy_if(inMap.begin(), inMap.end(), outMap.begin(), [](pair<double, pair<int, double>> item) {return (true) ;} // I have simplified the predicate 

However, when compiling, I get the following error:

error: use of deleted function 'std::pair<const double, std::pair<int, double>>& std::pair<const double, std::pair<int, double>>::operator=(const std::pair<const double, std::pair<int, double>>&)

Solution

  • The iterators of a std::map are not suitable for use with copy_if, as that algorithm is simply going to attempt to assign the entire value. However, the iterator of a std::map has a value type of std::pair<const K, V>, which means it is not copy assignable.

    However, you can use std::inserter to accomplish what you want

    std::copy_if(inMap.begin(), inMap.end(), std::inserter(outMap, outMap.end()), Predicate);