Soumen wrote:
Quote:
I need to write code to copy unique elements in from a sequence
container (say vector) to a set (or another sequence container will
do). Is following code efficient?
>
template <class T>
void copyUniqueObject(const vector<T &seqContainer,
set<T &uniqueSet)
{
std::copy(seqContainer.begin(), seqContainer.end(),
std::inserter(uniqueSet, uniqueSet.end()));
}
>
Or is there a better (more efficient) way (say, some way using
lower_bound or so) to write similar functionality?
Does using unique_copy over copy gives any advantage in this case?
>
Thanks in advance,
Regards,
~ Soumen
If your vector is sorted, *and* you don't mind mutating it, then using
'std::unique' on it might give you some advantage. If it isn't sorted,
and/or you don't want to mutate it, then your approach is sufficient.
The problem (as I see it) with 'std::set' is that its "insert" member
will have to attempt insertion every time, which means it will search
through the set more than necessary. Sorting the source container and
then using 'unique_copy' has the advantage of skipping the search for
any object that is equal to the one that was just inserted. You can use
'std::deque' as the destination container in that case (the fastest from
the insertion-at-end/indexed-retrieval POV).
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask