Trying to understand vectors

Hi all,

I am trying to understand why the following code fails to update the recordID in the Record objects. Is it something about the Record pointers returned by the vector class? Can someone explain what is going on? Thanks in advance for any help.

I am using gcc (4.4.1) on Linux.

Cheers

Sanders

The output:
Changing record no from -1 to 9
The new record no is -1
Changing record no from -1 to 9
The new record no is -1
Changing record no from -1 to 9
The new record no is -1
Changing record no from -1 to 9
The new record no is -1
Changing record no from -1 to 9
The new record no is -1

The Code:
#include <vector>
#include <iostream>

using namespace std;

class Record
{
public:
// Constructors
Record() { RecordNo = -1; }
~Record() {}
// Accessors
int getRecordNo() { return RecordNo; }
void setRecordNo(int value) { RecordNo = value; }

private:
int RecordNo;
};

int main(int argc, char *argv[])
{
vector<Record> dataset;
Record *record;
int newRecordNo = 9;

// Create a few records to add to the RecordCol
record = new Record();
dataset.push_back(*record);
record = new Record();
dataset.push_back(*record);
record = new Record();
dataset.push_back(*record);
record = new Record();
dataset.push_back(*record);
record = new Record();
dataset.push_back(*record);

// Iterate thru the records making changes as we go
vector<Record>::iterator pRecord = dataset.begin();
while (pRecord != dataset.end()) {
cout << "Changing record no from " << ((Record)*pRecord).getRecordNo() << " to " << newRecordNo << endl;
((Record)*pRecord).setRecordNo(newRecordNo);
cout << "The new record no is " << ((Record)*pRecord).getRecordNo() << endl;
++pRecord;
}

}
Pay attention to your types.

(Also, please use [code] blocks.)

1
2
3
4
vector <Record> dataset;
Record * record;
new Record;
push_back( *record )
list of (Record)
(Record *)
(Record *)
push_back a (Record)

Make them match:
1
2
3
4
5
6
7
8
vector <Record*> dataset;

dataset.push_back( new Record );

or

Record* record;
dataset.push_back( record );
list of (Record*)

push_back a (Record*)



(Record*)
push_back a (Record*)

Hope this helps.
((Record)*pRecord).setRecordNo(newRecordNo);

The (Record) above creates a temporary Record object, to which the new value is then assigned. The object in the vector remains unaffected.

Also, ((Record)*pRecord).getRecordNo() displays the value of a created temporary object as well.

You don't need casting here, and when you do, please use the C++ casting operators instead.
Duoas,

Cheers and thanks for the reply. I think that my types are okay but it seems that it will always pay to double check. Also thanks for the tip about code blocks.


Castaway,

Thanks. That fixes my problem. I didn't realise that casting created a new temp object but I guess that that makes sense. I thought that I needed the cast but when I took it away it worked. So 'cheers' to you too. Problem solved and more thanks.
Topic archived. No new replies allowed.