set 容器的用法


1.set容器的理解

  所有元素都會根據元素的鍵值自動排序,set元素的鍵值就是實值,實值就是鍵值。set不允許兩個元素有相同的鍵值。(set的元素不像map那樣可以同時擁有實值(value)和鍵值(key))。

set成員函數列表如下:

1. begin()--返回指向第一個元素的迭代器

2. clear()--清除所有元素

3. count()--返回某個值元素的個數

4. empty()--如果集合為空,返回true

5. end()--返回指向最后一個元素的迭代器

6. equal_range()--返回集合中與給定值相等的上下限的兩個迭代器

7. erase()--刪除集合中的元素

8. find()--返回一個指向被查找到元素的迭代器

9. get_allocator()--返回集合的分配器

10. insert()--在集合中插入元素

11. lower_bound()--返回指向大於(或等於)某值的第一個元素的迭代器

12. key_comp()--返回一個用於元素間值比較的函數

13. max_size()--返回集合能容納的元素的最大限值

14. rbegin()--返回指向集合中最后一個元素的反向迭代器

15. rend()--返回指向集合中第一個元素的反向迭代器

16. size()--集合中元素的數目

17. swap()--交換兩個集合變量

18. upper_bound()--返回大於某個值元素的迭代器

19. value_comp()--返回一個用於比較元素間的值的函數

 2.實現過程舉例:

#include<stdafx.h>
#include<set>
#include<iostream>
using namespace std;
int main()
{
    int arr[7] = { 0,1,2,3,4,5,3 };
    set<int> iset(arr, arr + 7);

    iset.insert(9);
    cout << "size:" << iset.size() << endl;
    cout << "3 count = " << iset.count(3) << endl;
    iset.erase(1);

    set<int>::iterator ite1 = iset.begin();
    set<int>::iterator ite2 = iset.end();
    for (; ite1 != ite2; ite1++)
    {
        cout << *ite1<<endl;
    }
    

    ite1 = iset.find(3);
    if (ite1 != iset.end())
        cout << "number 3 is in array " << endl;

    ite1 = iset.find(1);
    if (ite1 != iset.end())
        cout << "1 not found in array" << endl;
    system("pause");
    return 0;
}

結果:

set容器中初始化兩個數值3,但是是只插入一個,任意兩個元素之間的鍵值都是不相等的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM