14. 迴圈中刪除map元素的寫法
// for vector, deque
template <class Container, class T>
inline
void vector_erase(Container & c, T const& t)
{
c.erase(std::remove(c.begin(), c.end(), t), c.end());
}
template <class Container, class Pred>
inline
void vector_erase_if(Container & c, Pred pred)
{
c.erase(std::remove_if(c.begin(), c.end(), pred), c.end());
}
// for list, set, map
template <class Container, class T>
void list_erase(Container & c, T const& t)
{
typename Container::iterator
b = c.begin(), e = c.end(), prev = b;
while (b != e)
{
++b;
if (*prev == t) c.erase(prev);
prev = b;
}
}
template <class Container, class Pred>
void list_erase_if(Container & c, Pred pred)
{
typename Container::iterator
b = c.begin(), e = c.end(), prev = b;
while (b != e)
{
++b;
if (pred(*prev)) c.erase(prev);
prev = b;
}
}
typedef map<int,int> mymap;
typedef map<int,int>::iterator myiter;
mymap m; m[1] = 2; m[2] = -1; m[3] = 3; m[4] = 0; m[5] = -5; m[6] = 1;
myiter iter = m.begin();
while(iter!=m.end()) {
if(iter->second<0)
m.erase(iter++);
else
++iter;
}
4. 不要用錯string.find ,string::find_first_of ,find和find_first_of有本質區別
find是尋找子串在string出現的位置
find_first_of是尋找第一個匹配目標字串任何一個字元出現的位置。
(大多數的時候,需要的是find)
15. 從ifstream讀出一行到string,使用std::getline(ifstream的成員函數getline做不到)
10. 使用iterator的時候,自增或者自減,多使用++iter ,--iter的格式。
以下代碼是在C++環境下,實現一行一行地讀入文字文件
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ifstream in("your_file");
string line;
while (getline(in,line))
{
cout << line << "\n";
}
return 0;
}