Is it legal to write to std::string?

后端 未结 5 946
孤街浪徒
孤街浪徒 2020-12-03 21:21

In std::string there are only const members to fetch the data like c_str(). However I can get a reference to the first element of the string via operator[] and

5条回答
  •  Happy的楠姐
    2020-12-03 22:13

    Yes you can modify a string.

    You can also use it in algorithms that use iterators.

    You can not use it in the same way as a vector<> because there is no guarantee that elements are in contiguous memory locations (yet: coming to a standard near you soon).

    So if you modify your approach to use iterators rather than pointers it should work. And because iterators behave very much like pointers the code changes should be negligible.

    template
    void toupper(I first,I last_plus_one)
    {
        // Probably the same code as you had before.
    }
    
    
    {
         std::string  s("A long string With Camel Case");
    
         toupper(s.begin(),s.end());
    }
    

提交回复
热议问题