-3

How can I examine that the elements of the set are equal to zero? It is not working with find().

What do I have to use instead find()?

#include <iostream>
#include <set>
using namespace std;

int main()
{
    set<int> numbers;
    for(int j = 0; j < 10; j++)
    {
        if (numbers.find(j) == 0)
        {
            cout << "Yes.";   
        }
        else 
        {
            cout << "No."; 
        }
    }
    return 0;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
teki2021
  • 81
  • 5
  • 2
    You didn't ever put anything into your set, so what you're hoping to find there?? – πάντα ῥεῖ Nov 09 '21 at 23:23
  • 2
    Two other things: 1) A `std::set` contains unique elements, so either there will be one 0 or none. 2) [`find`](https://en.cppreference.com/w/cpp/container/set/find) returns an iterator, comparing this to the constant 0 makes no sense, and is the reason for the compiler error. – yano Nov 09 '21 at 23:26

1 Answers1

1

The following demonstrates how to search for 0 in a set.

#include <iostream>
#include <set>

void SearchForNum(const std::set<int>& numbers, int valToFind)
{
    // can use .find to look for 0
    if (numbers.find(valToFind) != numbers.end())
    {
        // find returned an iterator to an element in the set
        std::cout << "Found " << valToFind << std::endl;
    }
    else
    {
        // .find returned an iterator to the end of the set, 0 wasn't found
        std::cout << "Could not find " << valToFind << std::endl;
    }
}

int main()
{
    // first actually put something in the set
    std::set<int> numbers  {0, 1, 2, 3, 4, 5};
    std::set<int> numbers2 {1, 2, 3};

    SearchForNum(numbers, 0);  // zero found here
    SearchForNum(numbers2, 0); // not here

    return 0;
}

Demo

Also see Why is "using namespace std;" considered bad practice?

yano
  • 4,827
  • 2
  • 23
  • 35