set 類模板學習

set 類模板

set 類模板又稱爲集合類模板,一個集合對象像鏈表一樣順序地存儲一組值。在一個集合中,集合元素既充當存儲的數據,又充當數據的關鍵碼。

示例程序

#include <iostream>
#include <set>

using namespace std;

void main()
{
    set<char> cSet; //利用set對象創建字符類型的集合

    cSet.insert('B');
    cSet.insert('C');
    cSet.insert('D');
    cSet.insert('A');
    cSet.insert('F');

    cout << "old set:" << endl;

    set<char> ::iterator it;

    //按順序輸出顯示
    for(it = cSet.begin(); it!=cSet.end(); it++)
    {
        cout << *it << endl;
    }

    char cTmp;  //待查找字符

    //在集合中查找指定元素
    cTmp = 'D';
    it = cSet.find(cTmp);
    cout << "start find:" << cTmp << endl;
    if(it == cSet.end())
        cout << "not found" << endl;
    else
        cout << "found" << endl;

    //在集合中查找指定元素
    cTmp = 'G';
    it = cSet.find(cTmp);
    cout << "start find:" << cTmp << endl;
    if(it == cSet.end())
        cout << "not found" << endl;
    else
        cout << "found" << endl;
}

編譯報錯:

--------------------Configuration: test20160112 - Win32 Debug--------------------
Compiling...
main.cpp
f:\test20160112\main.cpp(49) : warning C4786: 'std::pair<std::_Tree<char,char,std::set<char,std::less<char>,std::allocator<char> 
Linking...

test20160112.exe - 0 error(s), 3 warning(s)

處理方式:

需要在源程序中的文件頭部添加以下代碼:

#ifdef WIN32
#pragma warning (disable: 4786)
#endif

出現這個錯誤的原因是VC6.0與STL之間不完全兼容,Debug下默認的字符長度最大爲255,而STL動態創建時有可能會超過255。

程序運行結果:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章