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。
程序运行结果: