对于 append 添加单个字符,有多种替代方法.可以添加包含单个字符的字符串str.append("b");.尽管这不完全相同,但效果相同.如前所述,有 operator+=还有push_back(),与其他标准容器一致重点是,它可能从未被视为用例(或足够强大的用例),因此,没有在 append 中添加合适的重载/签名来满足它.替代设计可能存在争议,但鉴于标准和此类的成熟度,它们不太可能很快被更改 - 它很可能会破坏大量代码.append 的替代签名也可以考虑;一种可能的解决方案可能是颠倒 count 和 char 的顺序(可能添加一个默认值);string&追加(CharT ch, size_type count = 1);另一个,如一些对basic_string的评论中所述 是去除append,实现的方法很多.I noticed thatstd::string str;str += 'b'; // worksstr.append('b'); // does not workstr.append(1, 'b'); // works, but not as nice as the previousIs there any reason why the append method does not support a single character to be appended? I assumed that the operator+= is actually a wrapper for the append method, but this does not seem to be the case. 解决方案 It is interesting to note that the form of append here;string& append( size_type count, CharT ch );Mirrors the constructor taking similar input.basic_string( size_type count, CharT ch, const Allocator& alloc = Allocator() );And some other methods that take a count with a character, such as resize( size_type count, CharT ch );.The string class is large and it is possible that the particular use case (and overload) for str.append('b'); was not considered, or the alternatives were considered sufficient.Just simple the introduction of a single overload for this could introduce ambiguity if the integrals int and char correspond (on some platforms this may be the case).There are several alternatives to the append adding a single character.Adding a string containing a single character can be done str.append("b");. Albeit that this not exactly the same, it has the same effect.As mentioned there is operator+=There is also push_back(), which is consistent with other standard containersPoint is, it was probably never considered as a use case (or strong enough use case), thus, a suitable overload/signature was not added to append to cater for it.Alternative designs could be debated, but given the maturity of the standard and this class, it is unlikely they will be changed soon - it could very well break a lot of code.Alternate signatures for append could also be considered; one possible solution could have been to reverse the order of the count and char (possibly adding a default);string& append(CharT ch, size_type count = 1);Another, as described in some of the critique of basic_string is to remove append, there are many methods to achieve what it does. 这篇关于为什么 std::string::append() 不如 std::string::operator+() 强大?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-18 14:27