Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

calling a function with paraneters of vector<int> and lambda function in main with an anonymous lambda?

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 informs me from the build output(VS 2019) that there is an signed/unsigned mismatch in my for loops. And it doesn’t print anything. And I have no clue why. Please help.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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. Use size_t as type of the loop counter.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading