簡體   English   中英

如何在Qt中使用STL算法?

[英]How to use STL algorithms in Qt?

在閱讀“ Qt 4的c ++ gui編程第二版”時,我遇到了這個話題:“ STL標頭提供了更完整的通用算法集。這些算法可用於Qt容器和STL容器。如果STL實現是在所有平台上都可用,當Qt缺乏等效算法時,可能沒有理由避免使用STL算法。”

它指出STL的通用算法(在“ algorithm”標頭中定義)也可以與Qt容器一起使用。 但是,當我運行以下代碼時,它顯示了一個錯誤“ sort:not found identifier”:

#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();
}

沒有使用Qt算法就可以解決它嗎?

為了擴展@Chernobyl的答案:C ++庫將所有標准容器,算法等放入名為std的命名空間中。 這意味着要使用它們,您必須將它們帶入全局名稱空間( using namespace std;using std::sort ),或者只是自己限定名稱std::sort(vec.begin(), vec.end());

兩種都可以。 這樣做的原因是,否則標准庫中的所有標識符都將有效地成為“保留字”,並且您將無法(輕松地)在程序中使用它們以供自己使用。 例如,沒有理由您不能自己編寫一個名為sort的函數,該函數sort特定的數據結構進行排序。 然后sort(..)將調用您的例程,而std::sort(..)將調用標准庫中的例程。 同上finderaseremovestringlist等。

此函數位於std名稱空間中,因此只需編寫:

#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();
}

或每次寫std::sort

#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();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM