与std :: string一起使用的std :: replace_copy的奇怪行为

use*_*061 0 c++ string stl

我有这个简单的代码:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string s = "1,0";
    string result;

    //result.resize(s.length());
    replace_copy(s.begin(), s.end(), result.begin(), ',', '.');

    cout << '"' << result         << '"' << endl;
    cout << '"' << result.c_str() << '"' << endl;
    cout << result.length() << endl;

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

result.resize取消注释行的此程序的控制台输出是:

"1.0"
"1.0"
3

-thats好的,但是当line with result.resize被注释掉时,输出是:

""
"1.0"
0

- 这会导致奇怪的错误,因为result != result.c_str()!!!

这种行为replace_copy(以及可能也是类似的模板)可能会被视为标准库中的错误吗?我找不到任何与此主题相关的内容.谢谢.

编译器:mingw32-g ++ 4.7.1

Lig*_*ica 5

你有什么期望?

如果没有resize,则新字符的字符串中没有空格.

试图复制到该空间无论如何肯定会导致"怪异"[read:undefined ]行为.你正在破坏你的记忆.

replace_copy复制到目标范围,这与将新元素插入目标容器不同.范围已经存在......

...除非你使用a back_inserter作为一种假范围,它实际上在引擎盖下进行插入:

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main()
{
    string s = "1,0";
    string result;

    //result.resize(s.length());   // Look, ma! No hands!
    replace_copy(
        s.begin(), s.end(),
        std::back_inserter<std::string>(result),
        ',', '.'
    );

    cout << '"' << result         << '"' << endl;
    cout << '"' << result.c_str() << '"' << endl;
    cout << result.length() << endl;
}

// "1.0"
// "1.0"
// 3
Run Code Online (Sandbox Code Playgroud)

现场演示

警告!在现场演示中获得正确的输出并不能证明什么,因为未定义的行为偶尔会"看起来有效".但是,我有96k代表你可以相信我.;)