473,606 Members | 2,200 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Why doesn't this list copy work?

Hello!
Consider the following complete program (with sample output). There's
something wrong with my call to std::copy() in the copy constructor of
the Unit class. It fails to copy the list. I could solve it by looping
manually through the argument's list and call push_back for each
element, but I'd like to know what's wrong with my std::copy() call.
Here's the code with sample output:
#include <algorithm> /* std::copy() */
#include <iostream>
#include <list>

class Unit
{
public:
Unit(int n)
{
m_list.push_bac k(n);
}

Unit(const Unit& u)
{
/* This call fails to copy the list. */
std::copy(u.m_l ist.begin(), u.m_list.end(), m_list.begin()) ;
}

void add_to_list(int n)
{
m_list.push_bac k(n);
}

void print_list() const
{
std::list<int>: :const_iterator itr = m_list.begin();

while(itr != m_list.end())
{
std::cout << *itr << std::endl;
++itr;
}
}

private:
std::list<int> m_list;
};

int
main()
{
Unit u1(4711);

u1.add_to_list( 123);
u1.add_to_list( 456);

Unit u2(u1);

std::cout << "Printing u1:" << std::endl;
u1.print_list() ;

std::cout << "Printing u2:" << std::endl;
u2.print_list() ;

return 0;
}
Sample output:
$ ./copyctor.exe
Printing u1:
4711
123
456
Printing u2:

Thanks for any replies!

/ E

Aug 11 '05 #1
3 1560
Eric Lilja wrote:
Hello!
Consider the following complete program (with sample output). There's
something wrong with my call to std::copy() in the copy constructor of
the Unit class. It fails to copy the list. I could solve it by looping
manually through the argument's list and call push_back for each
element, but I'd like to know what's wrong with my std::copy() call.
You can't copy something if the destination does not have enough space.
In your case, the Unit being copy-constructed is empty. You *must* use
insert() or push_back() on the list.

You have two solutions: either a manual loop or an iterator adaptor.
Here's the code with sample output:
#include <algorithm> /* std::copy() */
#include <iostream>
#include <list>

class Unit
{
public:
Unit(int n)
{
m_list.push_bac k(n);
}

Unit(const Unit& u)
{
/* This call fails to copy the list. */
std::copy(u.m_l ist.begin(), u.m_list.end(), m_list.begin()) ;
for (std::list<int> ::iterator itor=u.m_list.b egin();
itor!=u.m_list. end(); ++itor)
{
u.push_back(*it or);
}

or

std::copy(u.m_l ist.begin(), u.m_list.end(),
std::back_inser ter(m_list));
}

void add_to_list(int n)
{
m_list.push_bac k(n);
}

void print_list() const
{
std::list<int>: :const_iterator itr = m_list.begin();

while(itr != m_list.end())
{
std::cout << *itr << std::endl;
++itr;
}
}

private:
std::list<int> m_list;
};

int
main()
{
Unit u1(4711);

u1.add_to_list( 123);
u1.add_to_list( 456);

Unit u2(u1);

std::cout << "Printing u1:" << std::endl;
u1.print_list() ;

std::cout << "Printing u2:" << std::endl;
u2.print_list() ;

return 0;
}
Sample output:
$ ./copyctor.exe
Printing u1:
4711
123
456
Printing u2:

Jonathan

Aug 11 '05 #2
Eric Lilja wrote:
Hello!
Consider the following complete program (with sample output). There's
something wrong with my call to std::copy() in the copy constructor of
the Unit class. It fails to copy the list. I could solve it by looping
manually through the argument's list and call push_back for each
element, but I'd like to know what's wrong with my std::copy() call.
Here's the code with sample output:
#include <algorithm> /* std::copy() */
#include <iostream>
#include <list>

class Unit
{
public:
Unit(int n)
{
m_list.push_bac k(n);
}

Unit(const Unit& u)
{
/* This call fails to copy the list. */
std::copy(u.m_l ist.begin(), u.m_list.end(), m_list.begin()) ;
Use the following instead. Well implemented classes like STL will
implement safe copy constructors.

m_list = u.m_list;

}

void add_to_list(int n)
{
m_list.push_bac k(n);
}

void print_list() const
{
std::list<int>: :const_iterator itr = m_list.begin();

while(itr != m_list.end())
{
std::cout << *itr << std::endl;
++itr;
}
}

private:
std::list<int> m_list;
};

int
main()
{
Unit u1(4711);

u1.add_to_list( 123);
u1.add_to_list( 456);

Unit u2(u1);

std::cout << "Printing u1:" << std::endl;
u1.print_list() ;

std::cout << "Printing u2:" << std::endl;
u2.print_list() ;

return 0;
}
Sample output:
$ ./copyctor.exe
Printing u1:
4711
123
456
Printing u2:

Thanks for any replies!

/ E


vector u2 is not updated by std:copy() hence it will still appear empty!
The copy did work and is dangerous in this case as you need to be sure
enough memory is availble to copy to!
To copy the contents of a vector to another just use an assignment as
outlined below.

std::vector<int > a,b;
..
..
// initiase a with some values
..
..
b = a;

John B
Aug 11 '05 #3

"n2xssvv g02gfr12930" <n2************ *****@ntlworld. com> wrote in message
news:Xg******** *********@newsf e1-gui.ntli.net...
Eric Lilja wrote:
Hello!
Consider the following complete program (with sample output). There's
something wrong with my call to std::copy() in the copy constructor of
the Unit class. It fails to copy the list. I could solve it by looping
manually through the argument's list and call push_back for each
element, but I'd like to know what's wrong with my std::copy() call.
Here's the code with sample output:
#include <algorithm> /* std::copy() */
#include <iostream>
#include <list>

class Unit
{
public:
Unit(int n)
{
m_list.push_bac k(n);
}

Unit(const Unit& u)
{
/* This call fails to copy the list. */
std::copy(u.m_l ist.begin(), u.m_list.end(), m_list.begin()) ;


Use the following instead. Well implemented classes like STL will
implement safe copy constructors.

m_list = u.m_list;


Better yet:

Unit(const Unit& u):m_list(u.m_l ist){}

and your initializer list should contain all of your class' members in the
order they are declared in your clas declaration.

Jeff
Aug 11 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
1418
by: Nick L | last post by:
I've hit a brick wall on something that I'm guessing is pretty simple but it's driving me nuts. I noticed that with python lists, generally when you make a copy of a list (ie, List1 = List2) List1 just becomes a reference to List2 and any modifications done to List1 affects List2. Ok I can live with this but I want to make a completely seperate copy not attached to the original in anyway. So then I used this method. List1 = List2 . This...
1
8274
by: Joseph Barron | last post by:
Here is a SIMPLE problem that I'm trying to solve. It works in Netscape 6.2, but IE6 gives ""No such interface supported." Below are page1.htm and page2.htm . In page1.htm, there are two dropdown lists. If you change the selection of the left one (e.g. choose parentoption2), it should open up page2.htm in a popup window.
11
3067
by: Tony Johansson | last post by:
Hello! I have some problem with STL function remove I have two classes called Handle which is a template class and Integer which is not a template class. The Integer class is just a wrapper class for a primitive int with some methods. I don't show the Integer class because it will not add any information to my problem. Main is using some STL function Now to my problem.
149
25093
by: Christopher Benson-Manica | last post by:
(Followups set to comp.std.c. Apologies if the crosspost is unwelcome.) strchr() is to strrchr() as strstr() is to strrstr(), but strrstr() isn't part of the standard. Why not? -- Christopher Benson-Manica | I *should* know what I'm talking about - if I ataru(at)cyberspace.org | don't, I need to know. Flames welcome.
2
4021
by: johnny | last post by:
hi all, I wonder why this little script doesn't work, maybe it's the provider not allowing the use of load data infile ( I know some don't let users to run some tasks ), could you please tell me if the script it's right before I ask the provider ? I can insert data into the table using fgetcsv as well with no problems,but I would like to understand. TIA
43
2706
by: michael.f.ellis | last post by:
The following script puzzles me. It creates two nested lists that compare identically. After identical element assignments, the lists are different. In one case, a single element is replaced. In the other, an entire column is replaced. --------------------------------------------------------------------------------------- ''' An oddity in the behavior of lists of lists. Occurs under Python 2.4.3 (#69, Mar 29 2006, 17:35:34)
4
6200
by: Sin Jeong-hun | last post by:
List<List<T>a=param; List<List<T>b=a; If I change b, then a is get changed. I want another copy of a, that is completely independent of a. I used double-nested for loop to copy each element manually. Is there any more efficent way to do that? Something like, List<List<T>b=CreateClone(a); Thanks.
6
1932
by: Johnny Jörgensen | last post by:
I've got a usercontrol derived from a normal ComboBox that contains some special formatting code. On my main form I've got a lot of my custom comboboxes. I discovered a bug in the derived control and fixed it. But it still doesn't work for the controls already added to the form. It works fine for new instances of the control dragged from the toolbox to the form. I don't want to have to drag and drop new controls to exchange all my old...
12
2429
by: Mark S. | last post by:
Hello, The app in question is lives on a Windows 2003 server with .NET 2.0 running IIS 6. The page of the app in question processes 2000 get requests a second during peak loads. The app uses a Static Object. In this object is a generic List<String>. For every page request this list is looped over only reading not writing each value.
0
8439
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
8430
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8094
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6770
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
5966
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5465
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
3930
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
2448
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
0
1296
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.