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

Posted 西北逍遥

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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版)

 

 

以上是关于C++ 查找容器中两个连续且相等的数的主要内容,如果未能解决你的问题,请参考以下文章

c++怎么判断两数相等

知识点

Python 和 C++ 下字符串查找速度对比,你觉得Python适合算法竞赛吗

Python 数据结构与算法——从某个列表中找出两个彼此最接近但不相等的数

算法leetcode2176. 统计数组中相等且可以被整除的数对(rust和go重拳出击)

算法leetcode2176. 统计数组中相等且可以被整除的数对(rust和go重拳出击)