STL inplace_merge on user-defined objects

W

WL Yeow

What is the proper way to define a user defined object that is
'compatible' with STL?

I'm trying to use the inplace_merge() function. For example, I have a
wrapper class _String that contains only char* as a member. It has:
2 constructors:
_String(char*) and _String(const _String&), that uses strdup.
member fuction:
bool operator<(const _String&) const, that uses strcmp.

In my test program I have:

vector<_String> v;
v.push_back(a = _String("hello"));
v.push_back(b = _String("world"));
v.push_back(c = _String("apple"));
v.push_back(d = _String("ink"));

inplace_merge(v.begin(), v.begin()+2, v.end());

After this line, char* of _String a, b are wiped out!
Why?
It took me a while to know that I need to have a copy constructor but
that doesn't help in inplace_merge. What else is lacking?

Thanks in Advance.
 
M

Mike Wahler

WL Yeow said:
What is the proper way to define a user defined object that is
'compatible' with STL?

Must be copyable and assignable.
I'm trying to use the inplace_merge() function. For example, I have a
wrapper class _String that contains only char* as a member. It has:
2 constructors:
_String(char*) and _String(const _String&), that uses strdup.
member fuction:
bool operator<(const _String&) const, that uses strcmp.

In my test program I have:

vector<_String> v;
v.push_back(a = _String("hello"));
v.push_back(b = _String("world"));
v.push_back(c = _String("apple"));
v.push_back(d = _String("ink"));

inplace_merge(v.begin(), v.begin()+2, v.end());

After this line, char* of _String a, b are wiped out!
Why?
It took me a while to know that I need to have a copy constructor but
that doesn't help in inplace_merge. What else is lacking?

Assignment operator (and a destructor if you don't have one already).

Look up "Rule of Three".

-Mike
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top