ReplaceSorted in ReferenceCountedArray

Could we please have a ‘replacesorted’ method in ReferenceCountedArray (or a better place). The idea is that when we’re sorting, the comparator is a better judge of whether something is the same than pointer comparison.

It’s sort of addReplacingIfAlreadyAsThereDefinedByComparator(), if you get my gist.

I’m trying this:

[code] template
void replaceSorted (ElementComparator& comparator,
ObjectClass* newObject) throw()
{
lock.enter();
int index = findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed);
// Check the previous item, and if it’s a match, delete it first
if (index > 0 && index - 1 < numUsed && comparator.compareElements (newObject, this->elements [index - 1]) == 0)
{
–index;
remove (index);
}

	insert (index, newObject);
	lock.exit();
}

[/code]

Bruce

Ok, sounds like a useful request, as there’s no other class for holding a set of ref counted objects.

I’d probably call it “addOrReplace” though?

or maybe “addOrReplaceSorted”?..

How about this (slightly more efficient that yours, but untested, so needs a quick sanity-check)…

[code] template
void addOrReplaceSorted (ElementComparator& comparator,
ObjectClass* newObject) throw()
{
lock.enter();
const int index = findInsertIndexInSortedArray (comparator, this->elements, newObject, 0, numUsed);

    if (index > 0 && comparator.compareElements (newObject, this->elements [index - 1]) == 0)
        set (index - 1, newObject); // replace an existing object that matches
    else
        insert (index, newObject);  // no match, so insert the new one

    lock.exit();
}

[/code]

I’ll try that. On the assumption that all adds used this methods (so they aren’t existing dupes) does my code to detect a duplicate look right?

Would the matching item always show up one before, or might it end up one after?

Bruce

As long as your sort function works properly, I think it should work… Give it a good test though!