STL实列
// #include "stdafx.h" -如果使用预编译的头文件就包含这个头文件 #include <vector> // STL向量的头文件。这里没有".h"。 #include <iostream> // 包含cout对象的头文件。 using namespace std; //保证在程序中可以使用std命名空间中的成员。 char* szHW = "Hello World"; //这是一个字符数组,以”\0”结束。 int main(int argc, char* argv[]) { vector <char> vec; //声明一个字符向量vector (STL中的数组) //为字符数组定义一个游标iterator。 vector <char>::iterator vi; //初始化字符向量,对整个字符串进行循环, //用来把数据填放到字符向量中,直到遇到”\0”时结束。 char* cptr = szHW; // 将一个指针指向“Hello World”字符串 while (*cptr != '\0') { vec.push_back(*cptr); cptr++; } // push_back函数将数据放在向量的尾部。 // 将向量中的字符一个个地显示在控制台 for (vi=vec.begin(); vi!=vec.end(); vi++) // 这是STL循环的规范化的开始——通常是 "!=" , 而不是 "<" // 因为"<" 在一些容器中没有定义。 // begin()返回向量起始元素的游标(iterator),end()返回向量末尾元素的游标(iterator)。 { cout << *vi; } // 使用运算符 “*” 将数据从游标指针中提取出来。 cout << endl; // 换行 return 0; }分析:这个实验开始时将hello world字符串放在定义的字符指针中,然后定义了一个字符容器vec,然后定义了一个字符迭代器对象vi,将szhw赋值给cptr,while循环则将指针cptr所指的元素依次压入容器vec,,后面的for循环中vec.Begin游标指向容器的首位,后面的vec.end指向容器最后一位的下一位,For循环则将容器vi中的元素依次输出来。
#pragma warning(disable:4786) #include <iostream> #include <string> #include <map> using namespace std; typedef map<int, string, less<int> > INT2STRING; void main() { INT2STRING theMap; INT2STRING::iterator theIterator; string theString = ""; int index; theMap.insert(INT2STRING::value_type(0, "Zero")); theMap.insert(INT2STRING::value_type(1, "One")); theMap.insert(INT2STRING::value_type(2, "Two")); theMap.insert(INT2STRING::value_type(3, "Three")); theMap.insert(INT2STRING::value_type(4, "Four")); theMap.insert(INT2STRING::value_type(5, "Five")); theMap.insert(INT2STRING::value_type(6, "Six")); theMap.insert(INT2STRING::value_type(7, "Seven")); theMap.insert(INT2STRING::value_type(8, "Eight")); theMap.insert(INT2STRING::value_type(9, "Nine")); for (;;) { cout << "Enter \"q\" to quit, or enter a Number: "; cin >> theString; if(theString == "q") break; for(index = 0; index < theString.length(); index++) { theIterator = theMap.find(theString[index] - '0'); if(theIterator != theMap.end() ) cout << (*theIterator).second << " "; else cout << "[err] "; } cout << endl; } }分析:这个实验我们需要map这个关联容器,它提供一对一的数据处理能力,内部自建一棵红黑树,具有自动排序功能。刚开始先给map关联器取了一个别名INT2STRING,里面有两种数据类型int,string,less < int > 是一个约束器,指定比较大小的函数对象。接下来定义了INT2STRING的一个对象theMap。接下来又定义了一个游标theIterator,定义了一个字符串和整形index,然后将需要的数据插入到关联容器中采用的是value_type而非pair,后面的第一个for循环就是控制输入的字符串,第二个for循环就是将输入的数据依次在容器中查找。特别需要注意的是map关联容器是一一对应的关系,(*theIterator).second表示容器存入的第二位数据。