【问题标题】:string& and char* version of string::append(), string::replace() and string::compare()string& 和 char* 版本的 string::append()、string::replace() 和 string::compare()
【发布时间】:2011-12-30 04:55:42
【问题描述】:

std::string 中的两个重载函数引起了我的注意:

string& append(const string& str, size_t pos, size_t n);
string& append(const char* s, size_t n);

我很好奇为什么char*版本的string::append()没有提供额外的参数size_t pos,如下:

string& append(const char* s, size_t pos, size_t n);

对于其他两个函数,情况也一样:

int compare(size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2) const;
int compare(size_t pos1, size_t n1, const char* s, size_t n2) const;

string& replace(size_t pos1, size_t n1, const string& str, size_t pos2, size_t n2);
string& replace(size_t pos1, size_t n1, const char* s, size_t n2);

这些函数的 char* 版本缺少参数size_t pos2,它不如它们的 string& 对应物灵活。我的问题如下:

  1. std::string为什么要这样设计它的接口?
  2. 为什么char*版本函数没有size_t pos
  3. 这背后的考虑是什么?

感谢您的阅读!

【问题讨论】:

    标签: c++ string


    【解决方案1】:

    因为您只需将pos 添加到s

    str.append(ptr + pos, len);
    

    这并不是说它不是一个很好的速记,但他们(通常)只想最少添加必要的功能,而不是琐碎的包装类型。

    【讨论】:

    • 此外,str.append(ptr, pos, len); 仅比 str.append(ptr + pos, len); 短一个字符(这取决于您的空格习惯)。
    【解决方案2】:

    也许你可以简单地做str.append(s+pos, n);

    【讨论】:

      猜你喜欢
      • 2021-04-10
      • 2011-04-21
      • 1970-01-01
      • 2012-03-16
      • 2020-01-28
      • 1970-01-01
      • 2012-06-05
      • 1970-01-01
      • 2016-03-26
      相关资源
      最近更新 更多