简体   繁体   中英

Searching in std::set without iterator C++

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!

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.

It sounds like you want set::find()

if( fdsockets.find(fd) != fdsockets.end() )
{
      // my code
}

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

You probably mean

if(fdsockets.find(fd) != fdsockets.end())

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM