几种STL中常用的容器和类1
2008-01-09 14:58
363 查看
一、 string (字符串类) 1、 所需头文件:#include <string> 2、 几个常用的方法: Ø operator = 赋值操作 例: std::string str1; str1 = “abc”; std::cout << str1 << std::endl; 结果: abc Ø append 追加操作 例: std::string str1 = “abc”; str1.append(“def”); std::cout << str1 << std::endl; str1.append(“ghi”, 2); std::cout << str1 << std::endl; 结果: abcdef abcdefgh Ø c_str 返回const E*;等同于const char * 例: std::string str = “abc”; std::cout << str.c_str() << std::endl; 结果: abc 注意: printf(buf, “%s”, str); Error! printf(buf, “%s”, str.c_str()); OK! 使用c_str方法却无法取到/0后面的元素。 Ø find 查找 例: std::string str = “abc”; int iPos = str.find(“c”); std::cout << iPos << std::endl; 结果: 2 Ø iterator 叠代器 例:把str中‘/’替换为‘//’ std::string str = “c:/test/test/”; for (string::iterator iter = str.begin(); iter != str.end(); iter++) { if (*iter == ‘/’) *iter = ‘//’; } std::cout << str << std::endl; 结果: c:/test/test/ Ø length length方法可以取到/0符号后面数据的长度。 二、 ostringstream (字符串格式化) 1、 所需头文件:#include <sstream> 2、 几个常用的方法: Ø 清空 例: std::ostringstream stm; stm.str(“”); 注意:ostringstream类也有clear方法,但在某些时候不起作用。 Ø 格式化 例: std::string str = “abc”; int iData = 100; float fData = 8.5; void* pData = 0; std::ostringstream stm; std::string strResult; stm << str << iData << fData << pData; strResult = stm.str(); std::cout << strResult << std::endl; 结果: abc1008.500000000 三、 ifstream和ofstream (文件流操作) 1、 所需头文件:#include <fstream> 2、 几个常用的方法: 例: char buf[1024]; std::ifstream in(“filename”, ios::in|ios::binary); std::ofstream out(“filename”, ios::out|ios::binary); if (!in || !out) { std::cout << “open file error!” << std::endl; } if (!in.seekg(10)) { std::cout << “seek error!” << std::endl; } memset(buf, 0, sizeof(buf)); int nBytes = in.read(buf,sizeof(buf)).gcount(); out.write(buffer, nBytes); in.close(); out.close(); |
相关文章推荐
- 几种STL中常用的容器和类2
- STL中几种常用容器比较
- STL基础4:STL7个常用容器的比较
- C++常用STL汇总(以容器为主)
- 【C++】STL常用容器总结之九:集合set
- C++ STL中的常用容器浅谈
- STL常用容器总结——deque双向队列
- STL常用容器浅谈
- STL标准容器中内容的几种打印技巧
- C++ STL常用算法与容器
- STL常用容器
- STL常用容器详细解析
- STL容器及常用算法
- java swing几种常用容器简单实现
- 常用STL容器及算法举例
- 几种STL容器的基本用法[资料]
- STL中容器的常用函数
- stl标准容器的常用函数
- 【STL】常用容器的方法
- STL中常用容器的选择