By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,353 Members | 1,555 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,353 IT Pros & Developers. It's quick & easy.

string transform with different input and output

P: n/a
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.

Nov 3 '05 #1
Share this Question
Share on Google+
3 Replies


P: n/a

edgekaos wrote:
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

Nov 3 '05 #2

P: n/a
Sorry to reply to my own post, but...

in*****@gmail.com wrote:
edgekaos wrote:
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.


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

Nov 3 '05 #3

P: n/a
edgekaos wrote:
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);

--
Best regards,
Andrey Tarasevich
Nov 4 '05 #4

This discussion thread is closed

Replies have been disabled for this discussion.