如何在C ++中插入一组元素?

时间:2017-02-07 20:08:01

标签: c++ stl set

好的,这是一个简短的查询。

我有一个Set容器说a;

c = 5,d = 42是整数。

我想使用for循环插入中没有的集合中从5到42的所有整数。

我该怎么做?

最后,应该看起来像{5,6,7 .......,42}

1 个答案:

答案 0 :(得分:4)

这样的事情:

#include <algorithm>
#include <iostream>
#include <iterator>
#include <set>

template<class OutputIterator, class T>
OutputIterator iota_rng(OutputIterator first, T low, T high)
{
        return std::generate_n(first, high - low, [&, value = low]() mutable { return value++; });
} 

int main()
{
    std::set<int> s;
    iota_rng(std::inserter(s, s.begin()), 5, 43);
    for (auto elem : s) {
        std::cout << elem << ", ";    
    }
}

Live Example

range-v3 library(建议作为技术规范)中,您可以更简洁地写出:

#include <range/v3/all.hpp>
#include <iostream>
#include <set>

int main()
{
    std::set<int> s = ranges::view::iota(5, 43);
    for (auto elem : s) {
        std::cout << elem << ", ";    
    }
}

Live Example