简体   繁体   中英

How to use STL algorithms in Qt?

While reading "c++ gui programming eith Qt 4 , second edition " I came across this topic : "The STL header provides a more complete set of generic algorithms. these algorithms can be used on Qt containers as well as STL containers. If STL implementations are available on all your platforms, there is probably no reason to avoid using the STL algorithms when Qt lacks an equivalent algorithm ."

It states that the generic algorithms of STL(which is defined in "algorithm" header) can be used with Qt containers as well . But when I run the following code it shows an error that "sort: identifier not found" :

#include <QApplication>
#include <algorithm>
#include <QVector>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
 QVector<int>vec{9,6,10,5,7};
 sort(vec.begin(),vec.end());
    return a.exec();
}

Is there any way to fix it without using Qt Algorithms?

To expand upon @Chernobyl's answer: The C++ library puts all of the standard containers, algorithms, etc into a namespace named std . This means that to use them you have to either bring them into the global namespace ( using namespace std; or using std::sort ) or just qualify the name yourself std::sort(vec.begin(), vec.end());

Either one works fine. The reason for this is otherwise all of the identifiers in the standard library would effectively become "reserved words", and you would be unable to (easily) use them in your programs for your own use. For example, there's no reason you can't write a function called sort yourself, which sorts a particular data structure. Then sort(..) would invoke your routine, while std::sort(..) would invoke the one in the standard library. Ditto for find , erase , remove , string , list , and so on.

This function locates in std namespace, so just write:

#include <QApplication>
#include <algorithm>
#include <QVector>
using namespace std;//new line!

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
 QVector<int>vec{9,6,10,5,7};
 sort(vec.begin(),vec.end());
    return a.exec();
}

Or write std::sort every time:

#include <QApplication>
#include <algorithm>
#include <QVector>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
 QVector<int>vec{9,6,10,5,7};
 std::sort(vec.begin(),vec.end());
    return a.exec();
}

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