2017-02-07 43 views
-3

好吧,這是一個簡短的查詢。如何在C++中的集合中插入一系列元素?

我有一個Set容器說一個;

c = 5,d = 42是整數。

我想使用for循環在集合中插入所有從5到42的整數,而不使用

我該怎麼做?

最後一個看起來應該像{5,6,7 ......,42}

+2

使用while循環 – Sam

+4

http://en.cppreference.com/w/cpp/algorithm/iota和http://en.cppreference.com/w/cpp/container/set/insert過載五。 – user4581301

+0

執行此操作的最佳方法是使用for循環。你爲什麼要求其他方式? –

回答

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