zoukankan      html  css  js  c++  java
  • C++ Searching Element

    C++ 查找第一个匹配元素(Search First Matching Element)

    algostuff.hpp

    #ifndef ALGOSTUFF_HPP
    #define ALGOSTUFF_HPP
    
    #include <array>
    #include <vector>
    #include <deque>
    #include <list>
    
    #include <forward_list>
    #include <set>
    #include <map>
    #include <unordered_set>
    #include <unordered_map>
    
    #include <algorithm>
    #include <iterator>
    #include <functional>
    #include <numeric>
    #include <iostream>
    #include <string>
    
    //集合中添加元素
    template <typename T>
    inline void INSERT_ELEMENTS(T& coll, int first, int last)
    {
        for (int i = first; i <= last; ++i)
        {
            coll.insert(coll.end(), i);
        }
    }
    
    //输出集合中的元素
    template <typename T>
    inline void PRINT_ELEMENTS(const T& coll, const std::string & optcstr = "")
    {
        std::cout << optcstr;
        for (auto elem : coll)
        {
            std::cout << elem << "  ";
        }
        std::cout << std::endl;
    }
    
    //输出Map中的元素
    template<typename T>
    inline void PRINT_MAPPED_ELEMENTS(const T& coll, const std::string& optcstr = "")
    {
        std::cout << optcstr;
        for (auto elem : coll)
        {
            std::cout << "[" << elem.first << "," << elem.second << "]  ";
        }
        std::cout << std::endl;
    }
    #endif // !ALGOSTUFF_HPP

    search_element.cpp

    #include "algostuff.hpp"
    
    using namespace std;
    
    int main()
    {
        list<int> list1;
        INSERT_ELEMENTS(list1,1,9);
        INSERT_ELEMENTS(list1, 1, 9);
        PRINT_ELEMENTS(list1,"list:  ");
    
        list<int>::iterator pos1;
        pos1 = find(list1.begin(),list1.end(),4);
    
        list<int>::iterator pos2;
        if (pos1 != list1.end())
        {
            pos2 = find(++pos1,list1.end(),4);
        }
    
        if (pos1 != list1.end() && pos2 != list1.end())
        {
            copy(--pos1,++pos2,ostream_iterator<int>(cout,"  "));
            cout << endl;
        }
    
    
        system("pause");
        return 0;
    }

    list: 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9
    4 5 6 7 8 9 1 2 3 4
    请按任意键继续. . .

    代码参考:C++标准库(第2版)

  • 相关阅读:
    常用数字处理小技巧
    C# 绘制统计图(柱状图, 折线图, 扇形图) zhuan
    谈谈防 SQL 注入式攻击策略
    ASP.NET2.0小技巧--内部控件权限的实现
    宝刀不老: Cookie
    IP地址与子网掩码总结
    ASP.NET 2.0下实现匿名用户向注册用户的迁移(上) zhuan
    [翻译].net 2.0(c#)下简单的FTP应用程序 zhuan
    ASP.NET2.0自动搜索文件组成导航系统
    正则表达式实现资料验证的技术总结
  • 原文地址:https://www.cnblogs.com/herd/p/12143191.html
Copyright © 2011-2022 走看看