gpt4 book ai didi

c++ - 在集合或列表中按顺序查找缺失的数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:26 24 4
gpt4 key购买 nike

如果 std::setstd::list 包含自然数序列 (1, 2, 3..)。标准库中是否有查找丢失号码的函数?

最佳答案

您可以 std::mismatch() 使用自然数序列。为了节省空间,我认为 boost::counting_iterator 在这里可以创造奇迹:

#include <iostream>
#include <list>
#include <boost/iterator/counting_iterator.hpp>
int main()
{
std::list<int> l = {1,2,3,4,6,7,8,9};
auto i = mismatch(l.begin(), l.end(), boost::counting_iterator<int>(1));
if(i.first==l.end())
std::cout << "no missing numbers\n";
else
std::cout << "the first missing number is " << *i.second << '\n';

}

测试运行:

~ $ g++ -std=c++0x -pedantic -Wall -Wextra -o test test.cc
~ $ ./test
the first missing number is 5

关于c++ - 在集合或列表中按顺序查找缺失的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3055421/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com