std function

I want know how can you use std::function <int (std::vector)> , example or tutorial.
When i write this code i receive
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 int x = 0;
   std::function<int(std::vector<uint8_t>)> exampleLambda =
           [&x] (std::vector<uint8_t> data)->int // affich the message which you want.
    {
      x = 1;

      std::cout <<"hello from lambda\n";
    };


   std::vector<uint8_t> testData(512);

  int returnValue = exampleLambda(testData);

  std::cout << exampleLambda(testData) <<endl;



hello from lambda
hello from lambda
6324928



someone can explain me.
I want understand how can we use std::function
Thank's in advance

std::function<int(T)> (where T is some class/type) means that it's a function that takes in an object of type T, and returns an int. In your example, you never return anything. The value inside your "returnValue" variable is garbage.

 In lambda function:
18:5: warning: no return statement in function returning non-void [-Wreturn-type]
 In function 'int main()':
23:8: warning: unused variable 'returnValue' [-Wunused-variable]


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream>
#include <string>
#include <functional>
#include <cstdint>
#include <vector>

int main()
{
 int x = 0;
   std::function<int(std::vector<uint8_t>)> exampleLambda =
           [&x] (std::vector<uint8_t> data)->int // affich the message which you want.
    {
        x = 1;
        std::cout <<"hello from lambda\n";
        return 2 * x; // or whatever
    };

   std::vector<uint8_t> testData(512);

   int returnValue = exampleLambda(testData);
   std::cout << x << " " << returnValue << std::endl;
}
Last edited on
Topic archived. No new replies allowed.