create
1. insert
set<T> s;
s.insert(val);
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> s;
s.insert(5);
s.insert(1);
s.insert(90);
int a[] = {7, 8, 9};
s.insert(a, a + sizeof(a)/sizeof(int));
for (auto it = s.begin(); it != s.end(); it++) {
cout << *it << endl;
}
return 0;
}
1
5
7
8
9
90
set will be in order automatically
retrieve
1. find
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> myset;
set<int>::iterator it;
for (int i = 1; i <= 5; i++)
myset.insert(i * 10);
it = myset.find(20);
myset.erase(it);
myset.erase(myset.find(40));
it = myset.find(60);
if (it != myset.end())
myset.erase(it);
cout << "myset contains:";
for (it = myset.begin(); it != myset.end(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
myset contains: 10 30 50
2.count
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<string> myset;
set<int>::iterator it;
myset.insert("1");
myset.insert("1");
cout << myset.count("1") << endl;
cout << myset.count("2") << endl;
return 0;
}
1
0
delete
1. erase
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> myset;
set<int>::iterator it;
for (int i = 1; i < 10; i++)
myset.insert(i * 10);
it = myset.begin();
++it;
myset.erase(it);
myset.erase(40);
it = myset.find(60);
myset.erase(it, myset.end());
cout << "myset contains:";
for (it = myset.begin(); it != myset.end(); it++)
cout << ' ' << *it;
cout << '\n';
return 0;
}
myset contains: 10 30 50
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<string> myset;
set<int>::iterator it;
myset.insert("1");
int i = myset.erase("2");
cout << i << endl;
int j = myset.erase("1");
cout << j << endl;
return 0;
}
0
1
erase by value if erase succeeded return 1 failed return 0
|