STL相关

stringstream  int转string:

int num;
stringstream stream;  
stream<< num; 
string s; 
s=stream.str();   //此处也可以用 stream>>s

自定义sort的compare:

sort(map.begin(), map.end(), compare);

bool compare(int a, int b) {
        return a < b;
}
当函数简短时,也可以用c++11的lambda表达式写成下面的形式:

sort(map.begin(), map.end(), [](int a, int b) {
       return a<b; 
});


输出vector最小值:

vector<int> vec(arry,arry+size);
sort(vec.begin(),vec.end());
cout << "there is " << count(vec.begin(),vec.end(),*vec.begin());
cout << " min numbers,"<< "value:" << *vec.begin() << endl;

指针new and delete

int *arry = NULL;
int size=4;
arry = new int[size];
int i = 0;
while (i != size)
{
	cin >> arry[i++];
}

delete []arry;

通过迭代器遍历数组元素:

for (vector<int>::iterator iter = ivec.begin(); iter != ivec.end(); ++iter)
      *iter = 0;

查找并读取map中元素

使用下标word_count["foobar"] 有危险的副作用:如果该键不在map容器中,那么会插入一个具有该键的新元素。

不修改map对象的查询操作
   m.count(k)       返回m中k的出现次数   
   m.find(k)    若m容器中存在按k索引的元素,返回指向该元素的迭代器;
    若不存在,则返回超出末端迭代器

用count检查map中是否有某键存在

int occurs = 0;
if (word_count.count("foobar"))  //count returns 0 or 1
      occurs = word_count["foobar"];

查找元素并替换

int occurs = 0;
map<string, int>::iterator it = word_count.find("foobar");
if (it != word_count.end())  
      occurs = it->second;

iterator types in STL

在由前序遍历和中序遍历构建二叉树时,用到iterator 可以很方便的递归得解,那时用的输入是InputIterator, 那么一共有多少种Iterator, InputIterator 与其他Iterator又有何区别呢?

 "The C++ Standard Library: A Tutorial and Reference"中给出:

Iterator Category       Ability                                 Providers

Input iterator          Reads forward                           istream
Output iterator         Writes forward                          tream, inserter
Forward iterator        Reads and writes forward
Bidirectional iterator  Reads and writes forward and backward   list, set, multiset, map, multimap
Random access iterator  Reads and writes with random access     vector, deque string, array 
详情可见 :  http://stdcxx.apache.org/doc/stdlibug/2-2.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值