Change string by index

前端 未结 3 1511
借酒劲吻你
借酒劲吻你 2021-01-13 04:38

I am a beginner in C++ and I am currently working with strings.

My question is why when compiling the code I\'m providing below, I can get the string\'s characters w

3条回答
  •  一整个雨季
    2021-01-13 05:20

    The size of altered is always zero - by using indexes you are trying to copy values from original to altered at indexes altered does not have. As LogicStuff has said, this is undefined behaviour - it doesn't generate an error because when we use indexes with std::string we are in fact calling an operator on a std::string to access the data field of a string. Using [] operator is defined in the C++ Standard as having no range check - that's why no error was thrown. The safe way to access indexes is to use the at(i) method: altered.at(i) will instead throw a range error if altered.size() <= i

    However, I'm going to give this as my solution because it's a "Modern C++" approach (plus shorter and complete).

    This is the alternative I would do to what has been given above:

    string original = "abc";
    string altered = original;
    for (auto& c : altered) c += 5;  // ranged for-loop - for each element in original, increase its value by 5
    cout << altered << endl;
    

    Note the significant reduction in code :-)

    Even if I were doing it LogicStuff's way, I would still do it like this:

    string original = "abc"
    string altered = ""; // this is actually what an empty string should be initialised to.
    for (auto c : original) altered += (c+5);
    

    However, I actually don't recommend this approach, because of the way push_back() and string appending / string concatenation work. It's fine in this small example, but what if original was a string holding the first 10 pages of a book to be parsed? Or what if it's a raw input of a million characters? Then every time the data field for altered reaches its limit it needs to be re-allocated via a system call and the contents of altered are copied and the prior allocation for the data field is freed. This is a significant performance impediment which grows relative to the size of original -- it's just bad practice. It would always be more efficient to do a complete copy and then iterate, making the necessary adjustments on the copied string. The same applies to std::vector.

提交回复
热议问题