Why qBinaryFind is giving compilation errors for std::list?



  • Why qBinaryFind is giving compilation errors for std::list?

    Please go through the following examples?
    for example following program does not compile.
    int main(int argc, char *argv[])
    {
    QCoreApplication a(argc, argv);
    std::list<int> sl;
    int num ;
    for ( int i = 0 ; i < 20 ; i ++ )
    {
    sl.push_back ( i ) ;
    }
    std::cout <<"Enter the integer :: " ;
    std::cin >> num ;
    std::list<int>::const_iterator slItr = qBinaryFind ( sl , num );
    if ( slItr != sl.end () )
    std::cout <<"Num " << *slItr << " found " << std::endl;
    else
    std::cout <<"Num " << num << " not found " << std::endl;
    return a.exec();
    }

    http://www.boostprogramming.com/forum/index.php/topic,748.0.html



  • std::list does not have random access, it's a linked list not a vector, and qBinarySearch needs a container that has random access to the elements.

    So you can use qBinaryFind with a std::vector, but you will need the overload that takes two iterators to specify a range (not the overload that takes a container, because of the stl that has a cbegin() and cend() to return const iterators):

    @
    std::vector<int> sl; int num ;
    for ( int i = 0 ; i < 20 ; i ++ )
    { sl.push_back ( i ) ; }

    std::cout <<"Enter the integer ::";
    std::cin >> num ;
    
    std::vector<int>::const_iterator slItr = qBinaryFind( sl.cbegin(), sl.cend() , num );
    
    if ( slItr != sl.end () )
        std::cout <<"Num " << *slItr << " found" << std::endl;
    else
        std::cout <<"Num "<< num << " not found" << std::endl;
    

    @


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.