简体   繁体   中英

Inserters in C++ confusion

So I dont understand how to use inserters in this situation. I know what are inserters, I know about std::front_inserter and std::back_inserter and std::inserter but I am confused about this problem which I will present now. I need to make function, which will transform elemets of vector and put them in deque(or vector nevermind, its "generic" function anyway). That function has 5 parameters, which one of them is another function(which can have only one parameter, it is not specified what type(i mean it can be reference,iterator,pointer...... whatever)).

If my vector is:

std::vector<int> v={1,2,3,4,5};

I need to make some modification, with lambda function, which will make my deque have elements like this:

25 16 9 4 1

So you see that first element of deque is last element of vector ^2 (you can see what I want to do). So my question is: How can the problem be done using inserters? I mean should I somehow put inserter in lambda fucntion? Maybe lambda should be like this:

[](int x) { 
x=x*x;
std::front_inserter(q);
}

I was thinking about this but then I dont understand how will this lambda work when I send it as parameter of this "big" function? How it will know what is q inside big function?

I hope you understand what I want to do.

Here is example. So I have to make some function, and this is prototype(lets say it is void):

typename<template Type1, template Type2>
void Fun(Type1 p1,Type1 p2,Type2 p3,Type2 p4,void (*f)(std::remove_reference<decltype(*p1)>::type) );

Lets say that I have the following code in main:

int main() {
std::vector<int> v={1,2,3,4,5};
std::deque<int> d(5);
Fun(v.begin(),v.end(),d.begin(),d.end(), /* some lambda function */);

If you're only interested in the transformation, not in implementing a function with that type,

std::deque<int> d;
std::transform(v.begin(), v.end(), std::front_inserter(d), [](int x){return x * x;});

or

std::deque<int> d;
std::transform(v.rbegin(), v.rend(), std::back_inserter(d), [](int x){return x * x;});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM