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

posted @ 2020-01-03 09:17  西北逍遥  阅读(267)  评论(0编辑  收藏  举报