为什么C++标准要保留这样一个冗余函数呢?

Why does the C++ standard keep such a redundant function?

  1. std::string::find的原型:

    size_type find( CharT ch, size_type pos = 0 ) const;
    
  2. std::string::find_first_of的原型:

    std::size_type find_first_of( CharT ch, size_type pos = 0 ) const;
    

两者功能相同。但是很明显后者是多余的

我认为这种冗余会使用户感到困惑,因为 find_first_of 表示 "find anyone of the given characters",而不是 "find the given character"。

为什么C++标准会保留这样一个冗余函数?

它们之间存在 微妙的 区别。 Bjarne 将它们的用法阐明为:

The find_∗_of() functions differ from find() and rfind() by looking for a single character, rather than a whole sequence of characters.

string s {"accdcde"};
auto i1 = s.find("cd");           // i1==2 s[2]=='c' && s[3]=='d'
auto i2 = s.rfind("cd");          // i2==4 s[4]=='c' && s[5]=='d'
auto i3 = s.find_first_of("cd");  // i3==1 s[1]=='c'
auto i4 = s.find_last_of("cd");   // i4==5 s[5]=='d'

编辑:

正如@juanchopanza 正确观察到的那样,此说明与 OP 提供的重载版本(采用 char)并不完全相关。

Is there any rationale behind?

IMO,find_first_of( char, pos) 可以作为提供与其 对应签名 find_last_of( char, pos) 的一致性的案例,与 find(char, pos) 从左到右。

请注意 find(char, pos) 可以取代 find_first_of( char, pos) 但不能取代 find_last_of( char, pos)。缺少 find_first_of( char, pos) 可能会导致开发人员有些困惑,因此最好也有这个重载版本。

std::string::find and std::string::find_first_of不要执行相同的功能。

对于std::string::find

Finds the first substring equal to the given character sequence. Search begins at pos, i.e. the found substring must not begin in a position preceding pos.

对于std::string::find_first_of

Finds the first character equal to one of the characters in the given character sequence. The search considers only the interval [pos, size()).

仅集合为单个字符的情况下,参数为CharT,这两个函数巧合重复

我不是标准化委员会的成员,但不难理解为什么。

find()find_first_of() 都是函数族。

find() 查找子字符串。 find_first_of() 查找匹配的第一个参数中的第一个字符。当只指定一个字符时,在这两种情况下,它们做同样的事情。

通常,如果使用此类函数来解析字符串,开发人员将使用 find() 的多个重载(搜索子字符串)或 find_first_of() 的多个重载(搜索单个符合某些标准的字符),而不是混合使用两者,并依赖于所使用的各种函数之间的逻辑一致性。

虽然可以(逻辑上)混合使用两者,但迫使原本使用 find_first_of() 的开发人员使用 find(),反之亦然,这会使代码更难推理,因此更难正确,更难维护。

指定此类函数的工作量(在标准中,开发此类函数的工作量(一次,每次实现)比许多开发人员不得不更加努力地考虑他们使用的函数的工作量要少得多,因此更加努力地工作以使他们的程序正常工作,然后进行维护。