c++transformtolower

C++ transform parameter initialization question


I was trying to transform a string into lowercase and store it in another variable using std::transform and std::tolower. I first tried:

string str1("Hello");
string lowerStr1;
transform(str1.begin(), str1.end(), lowerStr1.begin(), ::tolower);
cout << lowerStr1 << endl;

But, lowerStr1 contained nothing. After initializing lowerStr1 with str1, I got the desired result. I want to know the intuition behind this. Could someone explain why lowerStr1 should be initialized in this case?


Solution

  • lowerStr1 is empty, and std::transform won't insert elements into it.

    std::transform applies the given function to a range and stores the result in another range, beginning at d_first.

    You can use std::back_inserter, which constructs a std::back_insert_iterator, which would call push_back() on the container to insert elements.

    transform(str1.begin(), str1.end(), back_inserter(lowerStr1), ::tolower);
    

    Or make lowerStr1 containing 5 elements in advance.

    string lowerStr1(5, '\0');
    transform(str1.begin(), str1.end(), lowerStr1.begin(), ::tolower);
    

    or

    string lowerStr1;
    lowerStr1.resize(5);
    transform(str1.begin(), str1.end(), lowerStr1.begin(), ::tolower);
    

    Could someone explain why lowerStr1 should be initialized in this case?

    That's because you initialize lowerStr1 containing 5 elements in advance as above. What's the value of the initialized elements doens't matter in fact.