On 11/16/2011 2:55 AM, Peter Liedermann wrote:
> On Tue, 15 Nov 2011 21:30:14 +0100, Marcel Müller
> <> wrote:
>
>> On 15.11.2011 20:50, Peter Liedermann wrote:
>>> Let "Jumbo" be the name of a class whose instances consume substantial
>>> storage.
>>>
>>> A vector of typically 1000 such Jumbo-instances is needed. It must be
>>> sorted by a simple int criterium, but not often.
>>>
>>> Is there a substantial performance difference between vector <Jumbo> and
>>> vector <Jumbo *>, provided that everything else is adapted accordingly?
>>> Is there a difference at all?
>>
>> In general you need to copy the Jumbo objects to put them into the
>> vector. The copy constructor of Jumbo might be quite expensive if it
>> is not a POD like type. Is that what you want?
>
> I think this is the key to my question: Jumbo * is a POD type and Jumbo
> itself is clearly not. For illustration of the term POD, I found
> http://www.fnal.gov/docs/working-gro...x/doc/POD.html
> useful.
Depending on what Jumbo looks like, you could still sort a
vector<Jumbo> efficiently if you can define an efficient swap()
overload. For instance, suppose Jumbo is implemented as follows:
struct Jumbo
{
std::string foo;
std::vector<double> bar;
} ;
Then you can define swap() by first defining a public swap() member
function:
void swap(Jumbo &rhs)
{
//Almost all the types in the standard library have efficient
swap() overloads
swap(foo, rhs.foo);
swap(bar, rhs.bar);
}
Then, define a global swap function in the same namespace as Jumbo (this
is important!)
inline void swap(Jumbo &lhs, Jumbo &rhs)
{
lhs.swap(rhs);
}
If you follow these two steps, and Jumbo consists solely of built-in
types and standard library types, then sorting a vector of Jumbo becomes
extremely efficient, with no need to ever allocate or deallocate memory
for a temporary object.
Joe Gottman