Re: expressing a certain algebraic statement in C++ STL

Discussion in 'C++' started by Mike Wahler, Apr 1, 2004.

  1. Mike Wahler

    Mike Wahler Guest

    "Razmig K" <> wrote in message
    news:...
    > Hello mates
    >
    > How do you express the test "Does the value x belong in the set S ?"
    > using the STL containers and algorithms ?


    #include <algorithm>
    #include <iostream>
    #include <ostream>
    #include <set>

    template <typename T>
    bool in_set(const std::set<T>& s, const T& value)
    {
    return s.find(value) != s.end();
    }

    std::eek:stream& operator<<(std::eek:stream& os,
    const std::set<int>& s)
    {
    std::copy(s.begin(), s.end(),
    std::eek:stream_iterator<int>(os, "\n"));

    return os;
    }

    void query(const std::set<int>& s, int value)
    {
    std::cout << "Value " << value << " is"
    << (in_set(s, value) ? "" : " not")
    << " in set\n";
    }

    int main()
    {
    std::set<int> my_set;

    for(int i = 0; i < 10; i +=2)
    my_set.insert(i);

    std::cout << "Values in set:\n" << my_set << '\n';
    query(my_set, 4);
    query(my_set, 5);

    return 0;
    }

    Output:

    Values in set:
    0
    2
    4
    6
    8

    Value 4 is in set
    Value 5 is not in set


    -Mike
     
    Mike Wahler, Apr 1, 2004
    #1
    1. Advertising

  2. Mike Wahler

    Razmig K Guest

    Yes. Since the std::set lookup implemented through member 'find'
    guarantees logarithmic complexity, the choice of std::set will
    hopefully be adequate.

    Thanks for the help.

    //rk
     
    Razmig K, Apr 1, 2004
    #2
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Michel Rosien
    Replies:
    0
    Views:
    367
    Michel Rosien
    Apr 22, 2004
  2. DennisNedry

    Algebraic Parser

    DennisNedry, Feb 2, 2005, in forum: C++
    Replies:
    6
    Views:
    882
    DennisNedry
    Feb 2, 2005
  3. steve
    Replies:
    3
    Views:
    268
    Paul Boddie
    Oct 23, 2006
  4. DavidM
    Replies:
    6
    Views:
    568
  5. Cristian
    Replies:
    9
    Views:
    577
    Victor Bazarov
    Aug 23, 2007
Loading...

Share This Page