Are there any disadvantages to this implementation of copy_if for a map? Is there a better way to do it? The goal is to copy elements from one map to the other if they satisfy the predicate without changing the source.
Note that the focus is on the copying inside the function, not on providing a generic algorithm similar to what copy_if would be.Code:#include <iostream>
#include <string>
#include <map>
void CopyIfOdd(const std::map<int, std::string>& source, std::map<int, std::string>& target);
bool IsOdd(int i) { return i % 2 ? true : false; }
int main()
{
std::map<int, std::string> allIntsToTen;
allIntsToTen.insert(std::make_pair(1, std::string("Odd")));
allIntsToTen.insert(std::make_pair(2, std::string("Even")));
allIntsToTen.insert(std::make_pair(3, std::string("Odd")));
allIntsToTen.insert(std::make_pair(4, std::string("Even")));
allIntsToTen.insert(std::make_pair(5, std::string("Odd")));
allIntsToTen.insert(std::make_pair(6, std::string("Even")));
allIntsToTen.insert(std::make_pair(7, std::string("Odd")));
allIntsToTen.insert(std::make_pair(8, std::string("Even")));
allIntsToTen.insert(std::make_pair(9, std::string("Odd")));
allIntsToTen.insert(std::make_pair(10, std::string("Even")));
std::map<int, std::string> allOddIntsToTen;
CopyIfOdd(allIntsToTen, allOddIntsToTen);
}
void CopyIfOdd(const std::map<int, std::string>& source, std::map<int, std::string>& target)
{
std::map<int, std::string>::const_reverse_iterator iterPair = source.rbegin();
std::map<int, std::string>::const_reverse_iterator iterEnd = source.rend();
std::map<int, std::string>::iterator iterLastInserted = target.end();
for (; iterPair != iterEnd; ++iterPair)
{
if (IsOdd(iterPair->first))
iterLastInserted = target.insert(iterLastInserted, *iterPair);
}
}