PDA

View Full Version : using QPair in QVector



damonlin
28th January 2009, 08:02
Dear All:
I use QPair in QVector when developing .
But there's some problem.
here is text example:


void test()
{
QVector< QPair< int , QString > > first;
QVector< QPair< int , QString > > second;

for(int iIdx = 0; iIdx <5 ; ++iIdx )
first.push_back(QPair< int , QString >(iIdx , "aaa") );

qCopy(first.begin(), first.end(), second.begin()); // it occurred errors
}

Is there any suggestion for me if I would like to copy from one vector to another ??
Thank you~~

wysota
28th January 2009, 08:06
What exact error are you getting?

seneca
28th January 2009, 08:58
qCopy assumes that the target elements allready exist and then overwrites them.

So this example must be:


void test()
{
QVector< QPair< int , QString > > first;

for(int iIdx = 0; iIdx <5 ; ++iIdx )
first.push_back(QPair< int , QString >(iIdx , "aaa") );

QVector< QPair< int , QString > > second(first.count());

qCopy(first.begin(), first.end(), second.begin());
}

Maybe this would be better:


void test()
{
QVector< QPair< int , QString > > first;

for(int iIdx = 0; iIdx <5 ; ++iIdx )
first.push_back(QPair< int , QString >(iIdx , "aaa") );

QVector< QPair< int , QString > > second(first);
}

Because it can share data until a write operation is made on either vector.

damonlin
28th January 2009, 09:20
Dear wysota:
There's a exception error at run time~~
And it broke at QBasicAtomicInt::deref()...

Dear seneca:
In my program, all I need to do is copy member to another member,
It means I have to use qCopy rather than constructor, does it ??

thank you~~

seneca
28th January 2009, 09:27
Using the copy constructor will have the same effect in practise, however the data stay shared as long as you don't change anything on either vector. As soon as you change something in the data, the data is physically copied behind the scenes and you continue with double memory.

Because this is completely transparent your application needs not wory about this. It is the same mechanism as when you copy a QString for example.

wysota
28th January 2009, 09:29
Seneca is right - you try to overwrite an unexisting item. You want to add items, not overwrite them.