zoukankan      html  css  js  c++  java
  • 循环中删除map元素的写法; 在C++环境下,实现一行一行地读入文本文档

    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)async&await
    多线程(4)Task
    多线程(3)ThreadPool
    多线程(2)Thread
    多线程(1)认识多线程
    泛型
    反射(4)反射性能问题:直接调用vs反射调用
    反射(3)反射应用:一个插件项目
    反射(2)使用反射
    反射(1)认识反射
  • 原文地址:https://www.cnblogs.com/cy163/p/733745.html
Copyright © 2011-2022 走看看