string transform with different input and output

E

edgekaos

Is method 2 valid?

Method 1:
wstring input = L"STRING";
wstring output = input;
transform(output.begin(), output.end(), output.begin(), towupper);

Method 2:
wstring input = L"STRING";
wstring output;
transform(input.begin(), input.end(), output.begin(), towupper);

I"m seeing crash under Visual Studio 2003 with method2.
 
I

int2str

edgekaos said:
Is method 2 valid?

Method 2:
wstring input = L"STRING";
wstring output;
transform(input.begin(), input.end(), output.begin(), towupper);

No, it's not. The output iterator needs to be the same length as the
input iterator.

Cheers,
Andre
 
I

int2str

Sorry to reply to my own post, but...

No, it's not. The output iterator needs to be the same length as the
input iterator.

OR, you can also use std::back_inserter(). Like so:

string input = "Hello World!";
string output;

transform( input.begin(), input.end(), back_inserter( output ), toupper
);

Cheers,
Andre
 
A

Andrey Tarasevich

edgekaos said:
Is method 2 valid?

Method 1:
wstring input = L"STRING";
wstring output = input;
transform(output.begin(), output.end(), output.begin(), towupper);

Method 2:
wstring input = L"STRING";
wstring output;
transform(input.begin(), input.end(), output.begin(), towupper);

I"m seeing crash under Visual Studio 2003 with method2.

The latter method is not valid. In order to make it valid you should either
pre-set the size of the destination string

wstring input = L"STRING";
wstring output(input.length(), 0);

transform(input.begin(), input.end(), output.begin(), towupper);

or use the 'back_insert_iterator' as the output iterator (see 'int2str's
messages), optionally reserving the required amount of memory in advance

wstring input = L"STRING";
wstring output;

output.reserve(input.length()); // <- optional

transform(input.begin(), input.end(), back_inserter(output), towupper);
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,901
Latest member
Noble71S45

Latest Threads

Top