avanish
avanish

Reputation: 43

what does here string function mean

string ans="";
int x=0,u=1,v=2,y=0;
ans+=string(u-x,'R');
ans+=string(v-y,'U');

Here what does string function actually store in ans variable

Upvotes: 1

Views: 149

Answers (3)

463035818_is_not_an_ai
463035818_is_not_an_ai

Reputation: 122133

Here

ans+=string(u-x,'R');

string(u-x,'R') is calling a constructor of std::string:

basic_string( size_type count,    
              CharT ch,
              const Allocator& alloc = Allocator() );

Constructs the string with count copies of character ch.

Further, there is a operator+= that appends one string to another.

Putting things together and simplifying the code a bit we get

std::string ans;                    // ans == ""
auto countR = 1;
auto countU = 2;
ans += std::string(countR,'R');     // ans += "R"  -> ans == "R"
ans += std::string(countU,'U');     // ans += "UU" -> ans == "RUU"

Upvotes: 2

rjhcnf
rjhcnf

Reputation: 1057

RUU.

The one of the constructors of string takes two arguments string (size_t n, char c); which construct the string instance with n times of c.

Upvotes: 0

Oliver Dain
Oliver Dain

Reputation: 9953

string ans="";

After this line ans is just "".

int x=0,u=1,v=2,y=0;
ans+=string(u-x,'R');

string(u-x, 'R') is equivalent to string(1 - 0, 'R') so that constructs a string with 1 copy of 'R' and then appends that to ans so now ans == "R".

string(v-y, 'U') is equivalent to string(2 - 0, 'U') so you end up with "RUU" as the final answer.

Upvotes: 4

Related Questions