C++ 查找容器中两个连续且相等的数

C++ 查找容器中两个连续且相等的数

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

adjacent_find1.cpp

#include "../CCommon_1/algostuff.hpp"

using namespace std;

bool doubled(int elem1,int elem2)
{
    return elem1 * 2 == elem2;
}

int main()
{
    vector<int> vec1;
    vec1.push_back(1);
    vec1.push_back(3);
    vec1.push_back(3);
    vec1.push_back(6);

    vec1.push_back(4);
    vec1.push_back(4);
    vec1.push_back(4);
    vec1.push_back(7);
    vec1.push_back(5);

    vec1.push_back(5);
    vec1.push_back(1);


    PRINT_ELEMENTS(vec1,"vec1:  ");

    vector<int>::iterator pos1;
    pos1 = adjacent_find(vec1.begin(),vec1.end());

    if (pos1 != vec1.end())
    {
        cout << "first two elements with equal value have position   " << distance(vec1.begin(),pos1) +1<< endl;
    }

    pos1 = adjacent_find(vec1.begin(),vec1.end(),doubled);
    if (pos1 != vec1.end())
    {
        cout << "first two elements with second value twice the     " 
            <<"first have pos. "<< distance(vec1.begin(), pos1) + 1 
            << endl;
    }

    system("pause");
    return 0;
}

vec1: 1 3 3 6 4 4 4 7 5 5 1
first two elements with equal value have position 2
first two elements with second value twice the first have pos. 3
请按任意键继续. . .

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

原文地址:https://www.cnblogs.com/herd/p/12153027.html