mercredi 17 août 2016

std::transform with lambda: skip some items

I have some C++11 code like

std::vector<std::string> names;
std::map<std::string, std::string> first_to_last_name_map;
std::transform(names.begin(), names.end(), std::inserter(first_to_last_name_map, first_to_last_name_map.begin()), [](const std::string& i){
    if (i == "bad")
        return std::pair<std::string, std::string>("bad", "bad"); // Don't Want This
    else
        return std::pair<std::string, std::string>(i.substr(0,5), i.substr(5,5));
});

where I'm transforming a vector to a map using std::transform with a lambda function. My problem is that sometimes, as shown, I don't want to return anything from my lambda function, i.e. I basically want to skip that i and go to the next one (without adding anything to the map).

Is there any way to achieve what I'm thinking about? I can use boost if it helps. I want to avoid a solution where I have to do a pre-process or post-process on my vector to filter out the "bad" items; I should only need to look at each item once. Also, my actual logic is a bit more complicated than the if/else as written, so I think it would be nice to keep things encapsulated in this std::transform/lambda model if possible (though maybe what I'm trying to achieve isn't possible with this model).

Aucun commentaire:

Enregistrer un commentaire