469,574 Members | 1,662 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,574 developers. It's quick & easy.

string transform with different input and output

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
3 2552

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
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
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.

Similar topics

9 posts views Thread by Patrick Guio | last post: by
reply views Thread by Christopher M. Lauer | last post: by
5 posts views Thread by z. f. | last post: by
6 posts views Thread by Vijai Kalyan | last post: by
4 posts views Thread by JJ | last post: by
1 post views Thread by patrickbeaudoin | last post: by
reply views Thread by suresh191 | last post: by
4 posts views Thread by guiromero | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.