从《C++标准库》里面看到的一些技巧,以及自己遇到的一些技巧,备忘。
- 从流中读取数据存入容器
1 copy(istream_iterator<string>(cin), istream_iterator<string>(), back_inserter(vInput));//从cin中读取string 类型的数据存入 vInput 这个vector
更多迭代器:http://www.cnblogs.com/L-hq815/archive/2012/08/28/2660714.html
这里的流可以是标准输入输出流,也可以是文件流,各种流了,然后就是各种容器
- 打印容器中的元素到流中去
1 copy(aDeque.begin(), aDeque.end(), ostream_iterator<int>(cout, " "));//向标准流中打印容器的元素
- 数字转字符串
在C++有两种字符串流,也称为数组I/O流,一种在sstream中定义,另一种在strstream中定义。它们实现的东西基本一样。sstream 是基于std::string编写的,strstream是基于C类型字符串char*编写的
string到int的转换
1 string result=”10000”; 2 int n=0; 3 stream<<result; 4 stream>>n;//n等于10000
更多资料:http://www.cppblog.com/Sandywin/archive/2008/08/27/27984.html
当然也有 atoi、itoa等一堆转换函数
以及sprintf、sscanf等一堆c语言的格式化函数
1 //伪代码 2 sstream ss; 3 ss << "C:\"<< num <<".jpg";
- Vector是动态增长的,当预先分配的内存不足的时候,会申请新的内存,这时需要移动前面所有的元素,会对性能造成很大影响(有时跑opencv的程序会崩掉)
vector.reserve()会保持一定的内存,vector的容量不会缩减(resize只会改变元素的个数),间接缩减容量的方法,两个vector交换之后,两者的容量也会交换。
- 一些数值的极值
1 #include<limits> 2 cout << "int max:" << numeric_limits<int>::max() << " int mini: " << numeric_limits<int>::min() << endl; 3 cout << "float max:" << numeric_limits<float>::max() << " float min: " << numeric_limits<float>::min() << endl;
//删除容器中所有为3的值
type::iterator newEnd = remove(aDeque.begin(), aDeque.end(), 3); distance(newEnd,aDeque.end())//删除元素的个数 aDeque.erase(newEnd,aDeque.end())//真正删除元素
比如输入序列为:1 2 3 4 5 6 7 8
要删除 3
则remove后变为 1 2 4 5 6 7 8 8 元素的个数和end()的指向都没有变连大小都没有变(应该移除的元素被后面的元素覆盖)
erase() 后才真正将大小和end()的位置改变
总结起来就是一句话
xx.erase(remove(xx.begin(),xx.end(),xx),xx.end());
产生原因:
迭代器和容器是分开的,虽然达到了最大的灵活性,但是迭代器无法调用容器的任何方法
- bind2nd(greater<int>(), 4)将greater<int>(x,y) 的第二个参数绑定为4 ,即相当于greater<int>(x,4)
- bind1st绑定的是第一个参数
书中还有更加详尽的各种标准库组件的使用,可以当做手册。
- C++ 11中的一些新特性
http://my.oschina.net/wangxuanyihaha/blog/183151
- vs2013 已经支持tr1、tr2
- http://cs.stmarys.ca/~porter/csc/ref/tr1_boost.html
- 利用tr2 中的一些函数实现的遍历文件夹(原本是boost的函数引入的)
1 // tr2.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdafx.h" 5 #include <iostream> 6 #include <filesystem> 7 #include <vector> 8 using namespace std::tr2::sys; 9 using namespace std; 10 11 int _tmain(int argc, _TCHAR* argv[]) 12 { 13 path mypath = "c:\Users"; 14 cout << "path_exists = " << exists(mypath) << ' '; 15 cout << "is_directory = " << is_directory(mypath) << ' '; 16 cout << "is_file = " << std::tr2::sys::is_empty(mypath) << ' '; 17 directory_iterator begin_iter(mypath),end_iter; 18 for (; begin_iter != end_iter; ++begin_iter){ 19 path filePath = begin_iter->path(); 20 cout << (is_directory(filePath) ? "目录" : "文件") << " " << "完整路径: " << std::tr2::sys::complete(filePath)<<endl; 21 } 22 23 cin.get(); 24 return 0; 25 }
未完待续……