Home > Blockchain >  Calling a function with parameters of vector<int> and lambda function in main() with an anonym
Calling a function with parameters of vector<int> and lambda function in main() with an anonym

Time:06-08

Question:

Using the following unfinished function (finish it), call it in the main function with an anonymous lambda function as a parameter and print all numbers that are NOT divisible by 2, 3 and 5.

vector<int> izdvoji(vector<int>& x, function<bool(int)> kriterij);
int main()
{
  vector<int> brojevi = { 1, 4, 5, 7, 3, 6, 12, 65, 32, 8, 87, 55, 23, 22, 1, 1, 433, 66, 7, 433, 3, 32, 76, 8, 72, 256, 42 };

  vector<int> rez = izdvoji(brojevi, /*lambda function*/);

  for (int i = 0; i < rez.size(); i  )
      cout << rez[i] << " ";
  //output: 1 7 23 1 1 433 7 433

  return 0;
}

My Answer:

#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <iterator>
#include <functional>
using namespace std;

//2 3 5 djeljivvost

vector<int> izdvoji(vector<int>& x, function<bool(int)> kriterij) {
    vector<int> rez;
    for (int i = 0; i < x.size(); i  ) {
        if (kriterij(x[i])) {
            rez.push_back(x[i]);
        }
    }
    return rez;
}



int main()
{
    vector<int> brojevi = { 1, 4, 5, 7, 3, 6, 12, 65, 32, 8, 87, 55, 23, 22, 1, 1, 433, 66, 7, 433, 3, 32, 76, 8, 72, 256, 42 };

    vector<int> rez = izdvoji(brojevi, [](int x)->bool {
        return !(x % 2 || x % 3 || x % 5);
    });

    for (int i = 0; i < rez.size(); i  )
        cout << rez[i] << " ";
    //output: 1 7 23 1 1 433 7 433

    return 0;
}

When I compile it, it says there are no issues found, but also it informs me from the build output (VS 2019) that there is a signed/unsigned mismatch in my for loops, and it doesn't print anything. I have no clue why.

CodePudding user response:

Your condition is wrong. Try for example 31, which is not divisible by 2, 3 or 5:

return !(31 % 2 || 31 % 3 || 31 % 5);
return !(   1   ||   1    || 1 );
return !(   true );
return false;

Check divisiblity by x % n == 0:

return !(x % 2 == 0 || x % 3 == 0 || x % 5 == 0);

For the warning about unsigned vs signed comparison, you need to consider that size() returns an unsigned value. Use size_t as the type of the loop counter.

  • Related