Hi guys, I'm trying to read data from an excel "csv" file and save it in a list. the problem is that I want to have a copy of this list named "list1" that will not change during the manipulations and claculations, because when I copied the contents of "list1" to "list2", The content of list2 changed through the program. Can anybody help me on this?

class FileInfo
{
    public:
    int a;
    float b;
    int c;
    int d;
    int e;
    int f;
};


// create lists
list<FileInfo*>list1;

list<FileInfo*>list2;


//read from excel file
void FileInput()
{
//DownloadList_test
ifstream file ("test.csv"); // declare file stream
string value1;
string value2;
string value3;
string value4;
string value5;
string value6;
string value7;
string value8;
string value9;

for (int t=0;t<5;t++) //read five lines only
{
 if (file.good())
{
     getline(file,value1, ','); // read a string until next comma
     getline(file,value2, ',');
     getline(file,value3, ',');
     getline(file,value4, ',');
     getline(file,value5, ',');
     getline(file,value6, ',');
     getline(file,value7, ',');
     getline(file,value8, ',');
     getline(file,value9);


//push values in memory & in list1
FileInfo* fi = new FileInfo();
fi->a = atoi(value1.c_str());
fi->b= atof(value3.c_str());
fi->c= atoi(value5.c_str());
fi->d= atoi(value7.c_str());
fi->e= atoi(value8.c_str());
fi->f= atoi(value9.c_str());

list1.push_back(fi);
}
}
file.close();
}



int main()
{

FileInput(); //read csv file

cout << "Copy contents of list1 to list2: ";
list<FileInfo*>::iterator p = list1.begin();
while(p != list1.end()) {
    cout<<endl;
  list2.push_back(*p);
p++;
}

.
.
.

return 0;
}

When you copy the elements of list1 into list2, you're copying the pointers to the FileInfo objects, so that list1[i] and list2[i] both point to the same allocated FileInfo instance.

Either create a copy-constructor

FileInfo(const FileInfo &other):
    a(other.a), b(other.b), ...
{}

or make your lists of <FileInfo> instead of <FileInfo *>.

Definitely, store them by value in the list, i.e. as list<FileInfo>. One advantage of linked-lists is that it almost never has to copy elements of the list (when inserting / deleting). So, you won't get any real penalty for storing a fairly large object by value in the list, if fact, that's the intended use.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.