迴圈中刪除map元素的寫法; 在C++環境下,實現一行一行地讀入文字文件

來源:互聯網
上載者:User
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;
}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.