lundi 13 janvier 2020

Converting std::vector container into an std::set using std::transform

More specifically I have a vector of some struct

std::vector<SomeStruct> extensions = getThoseExtensions();

where someStructVariable.extensionName returns a string.

And I want to create a set of extensionName, something like this std::set<const char*>.

Process is fairly straightforward when done using some for loops but I want to use std::transform from <algorithm> instead.


std::transform has four parameters.

1,2. First range (to transform first range from and to)

3. Second range/inserter (to transform second range)

4. A function


This is what I have so far

auto functionPointer = 
    [](SomeStruct x) -> const char* { return x.extensionName; };

 std::transform(availableExtensions.begin(),
                availableExtensions.end(),
                std::inserter(xs, xs.begin()),
                functionPointer);

because there's no "proper context" for std::back_inserter in std::set I'm using std::inserter(xs, xs.begin()).


The problem is I'm trying to return stack mem in my lambda function. So how do I get around this problem?

Oddly enough if I remove return from the function it works just like I expect it to! But I don't understand why and that strikes fear of future repercussion.

Aucun commentaire:

Enregistrer un commentaire