set的基本使用

构造一个集合

现在我们来构造一个集合。 C++ 中直接构造一个 set的语句为: sets。这样我们定义了一个名为 s的、储存 T类型数据的 集合,其中 T是集合要储存的数据类型。初始的时候 s是空集合。

插入元素

C++ 中用 insert()方法向集合中插入一个新的元素。注意如果集合中已经存在了某个元素,再次 插入不会产生任何效果,集合中是不会出现重复元素的。

删除元素

C++ 中通过 erase()方法删除集合中的一个元素,如果集合中不存在这个元素,不进行任何操作。

查找元素

C++ 中如果你想知道某个元素是否在集合中出现,你可以直接用 count()方法。如果集合中存在我 们要查找的元素,返回 1,否则会返回 0。

遍历元素

C++ 通过迭代器可以访问集合中的每个元素,迭代器就好比指向集合中的元素的指针。

清空

C++ 和 Java 中都只需要调用 clear()方法就可清空 set或者 HashSet。

C++ set 方法总结

方法        功能

insert      插入一个元素

erase      删除一个元素

count       判断元素是否在 set中

size          获取元素个数

clear         清空

代码

#include <set>
#include <string>
#include <stdio.h>
using namespace std;
int main() {
    set<string> country;  // {}
    country.insert("China"); // {"China"}
    country.insert("America"); // {"China", "America"}
    country.insert("France"); // {"China", "America", "France"}
    country.erase("America"); // {"China", "France"}
    country.erase("England"); // {"China", "France"}如果集合中不存在这个元素,不进行任何操作。
    if (country.count("China")) {
        printf("China belong to country");
    }
    for (set<string>::iterator it = country.begin(); it != country.end(); ++it) {
        cout << (*it) << endl;
    }//遍历set 
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/KyleDeng/p/9261813.html