当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - How to add elements of a std::set to another non-empty set?

问题描述:

 set<int> A, B;

for (int i = 0; i < 100; i++) A.insert(i);

for (int i = 50; i < 150; i++) B.insert(i);

How to add elements of set B to the set A?

In another words, how to implement A = Union(A, B)?

网友答案:

By default sets are unique values only and sorted so inserting the iterator range should work:

A.insert(B.begin(), B.end());
网友答案:
A.insert(B.begin(), B.end());      // done
网友答案:

Use

template <class InputIterator>
void std::set::insert( InputIterator first, InputIterator last );
网友答案:

You can use another overload of insert which takes a pair of iterators as:

A.insert(B.begin(), B.end());

The above code copies the elements (which do not exist in A) from B to A (which means you don't need to handle the duplicates manually).

Have a look at all the overloads of insert here:

  • All overloads of std::set::insert
分享给朋友:
您可能感兴趣的文章:
随机阅读: