2

I need to sort a collection of Element. Is there any specific advantage of sorting a vector of Element* i.e

std::vector<Element*> vectRef;

to sorting a vector of Element.

std::vector<Element> vect;

assuming I write the comparator accordingly.

Element struct is show below:

struct Element
{
    Record *elm;        

    Element(Record *rec)
    {
        elm = new Record();
        //...copy from rec
    }
    ~Element()
    {
        delete elm;
    }
};
Nav
  • 19,885
  • 27
  • 92
  • 135
ajay
  • 461
  • 1
  • 4
  • 6
  • If you're working with pointers, you'd want to try out ptr_vector of the boost pointer containers. They're a god-send! (I edited the title to 'vector of pointers' since there is no such thing as 'vector of references') – Nav Feb 18 '11 at 05:50
  • Something you may find intriguing if you're inquisitive: http://stackoverflow.com/questions/4342957/why-does-vector-not-have-sort-method-as-a-member-function-of-vector-while-list – Nav Feb 18 '11 at 05:54

2 Answers2

2

How expensive is Element's copy constructor? Does it do a deep copy of the contained Record object? Sorting a vector<Element> will require many copies of Element objects unless swap is overloaded properly. I'm not sure what the rules are about whether sort must use swap and if it must use a user's overloaded version of swap; http://accu.org/index.php/journals/466 has some information about that. Sorting vector<Element*> will only be copying pointers around, which is likely to be cheaper. C++0x changes this, assuming Element has an efficient move constructor and move assignment operator.

Jeremiah Willcock
  • 30,161
  • 7
  • 76
  • 78
0

It depends on how copying of Elements is done. As you've shown it above, an Element contains a pointer to a Record, but doesn't define a copy constructor. If that's correct, copying Element objects should be cheap and quick, so you'd gain little or nothing by storing pointers to Elements.

At the same time, I have to point out that doing shallow copies can easily introduce errors. When/if you change Element to do deep copying, you might gain a lot more from storing and sorting pointers instead of Element objects (but it'll depend on how expensive it is to copy a Record).

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111