开发者

std::set and its front_insert_iterator

I know I can do this:

std::vector<double> vec;
std::back_insert_iterator<std::vector<double> > it( back_inserter(vec) );
it = 4.5;

But I'd like to do something similar (in syntax) to std::set (and use a front_insert_iterator instead of a reference to the set and use set::insert). Is it possible, or am I forced to use a reference o the set? Maybe I should use std::merge and/or std::set_intersect (this would allow for good error reporting in case of duplicates)? Would this be开发者_运维百科 a good approach?

Thanks!


You don't push_back or push_front to set, because (conceptually) a set is a sorted associative container. You can do this, though:

#include <cstdlib>
#include <set>
#include <iterator>
using namespace std;

int main()
{
    typedef set<int> MySet;
    MySet si;
    insert_iterator<MySet> it(si, si.begin());

    *it = 1;
    *it = 2;

}

EDIT:

Note that the begin() that the iterator is initialized with is not where the elements get put. Rather, it is a hint to the STL where to start looking for where to put the item.

EDIT2:

As per the comments below, you also wanted a way to check the "disposition" of the inserted item. That is, a way to tell if the item was or was not already present before you inserted it.

You cannot do this directly using only the iterator. If you need this information, you have two choices.

1) Don't use the insert iterator. The only way to get the bool you get from set::insert is to call set::insert. So call set::insert

42) Check the size of the set both before and after insertion. If the size grew by one, the item was inserted. :) I've market this as item #42 because IMO it is much less favorable than just calling insert directly for a number of reasons. There may be multithreading issues, there may be a performance hit in computing size(), etc.


You can't insert to the "back" or "front" of a set. Perhaps what you're looking for is std::inserter.

http://stdcxx.apache.org/doc/stdlibref/insert-iterator.html


To use front_insert_iterator the container must have member push_front defined (such as standard containers deque and list).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜