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版)

  • 相关阅读:
    R的卸载和更新安装
    Holt-Winters原理和初始值的确定
    使用excel结合线性规划求解Holt-Winters参数
    Java_Number(装箱和拆箱)
    Java_运算符
    Java_Character类
    Java_String&StringBuilder&StringBuffer类
    Java_数组
    Java_修饰符
    Java_变量类型
  • 原文地址:https://www.cnblogs.com/herd/p/12143191.html
Copyright © 2011-2022 走看看