3

I have std::set which contains come int values. Now i use iterator to find out whether set contans value.

But my application use this search very ofter and search using iterator too slow, can i do something like that:

std::set<int> fdsockets;

void myfunc(int fd)
{
    if(fdsockets[fd] != fdsockets.end())
    {
            // my code
    }
}

But i have error when compile using G++

no match for 'operator[]' in 'fdsockets[fd]'

Maybe i can use something instead of std::set?

Thanks!

Roman
  • 1,377
  • 2
  • 11
  • 12

4 Answers4

4

std::unorered_set or an ordered vector with binary search are more effective for simple membership test. If the maximum value of intergers is low a lookup table might be an alternative.

hansmaad
  • 18,417
  • 9
  • 53
  • 94
  • 2
    A sorted `vector` with binary search is only more effective if you rarely add or remove elements from the vector. Each insert or removal takes nlgn time. But the searches will be much faster. – Yakk - Adam Nevraumont Nov 09 '12 at 13:18
  • You are right. binary search or static tables are for static data only. – hansmaad Nov 09 '12 at 13:20
  • @Yakk That's not certain. It depends on the size of the data set as well. And copying `int` is a very cheap operation; insertions and deletions, even in a moderately large data set, may be cheaper using a sorted vector than using `std::set`: you can copy a lot of data for the price of one allocation (and finding where to insert is also cheaper). – James Kanze Nov 09 '12 at 14:26
4

It sounds like you want set::find()

if( fdsockets.find(fd) != fdsockets.end() )
{
      // my code
}
Benj
  • 31,668
  • 17
  • 78
  • 127
2

There is no operator[] in std::set.

You probably mean

if(fdsockets.find(fd) != fdsockets.end())
Emilio Garavaglia
  • 20,229
  • 2
  • 46
  • 63
0

If you don't need the iterator that set::find returns (you're just testing existence, not actually going to access the fdsocket), here's an alternative:

if(fdsockets.count(fd))
{
        // my code
}
Cubbi
  • 46,567
  • 13
  • 103
  • 169