insert [C++ Reference]
Keywords: stl,set,insert
Date: 2009-09-05T08:12:59-0700

[[insert]]
C++ Reference
Translations of this page?:

- en
- br-pt
- cn
- fr
- it
- jp
- pl
- ru
- tr

## insert

Syntax:

        #include <set>
        pair<iterator, bool> set::insert(const TYPE& val);
                    iterator set::insert(iterator pos, const TYPE& val);
                        void set::insert(input_iterator start, input_iterator end);

The method insert() either:

- inserts val before the element at pos (where pos is really just a suggestion as to where val should go, since sets and maps are ordered), and returns an iterator to that element.
- inserts a range of elements from start to end.
- inserts val, but only if val doesn't already exist. The return value is an iterator to the element inserted, and a boolean describing whether an insertion took place. If bool is false, the iterator points to where the element already was.

For example, the following code uses insert to populate a set of integers:

      const int max_nums = 10;
      int nums[max_nums] = {3,1,4,1,5,9,2,6,5,8};

      set<int> digits;
      for( int i = 0; i < max_nums; ++i ) digits.insert(nums[i]);

      cout << "Unique digits are: ";
      for( set<int>::const_iterator iter = digits.begin();
           iter != digits.end();
           ++iter ) {
        cout << *iter << ' ';
      }
      cout << '\n';

When run, this code displays:

    Unique digits are: 1 2 3 4 5 6 8 9

Related Topics: begin, end

Edit this page • Old revisions
• • • Login • Index • Recent changes • RSS • cc •