c++ - 使用 ostringstream 时出现意外行为
问题描述
在以下情况下获得不同的输出
std::string temp, temp1 = "foo", temp2 = "bar";
std::vector<char> test;
std::ostringstream s;
s << temp1;
temp = s.str();
std::copy(s.str().begin(), s.str().end(), std::back_inserter(test));
std::copy(temp2.begin(), temp2.end(), std::back_inserter(test));
std::cout << &test[0];
输出:foo
std::string temp, temp1 = "foo", temp2 = "bar";
std::vector<char> test;
std::ostringstream s;
s << temp1;
temp = s.str();
std::copy(temp.begin(), temp.end(), std::back_inserter(test));
std::copy(temp2.begin(), temp2.end(), std::back_inserter(test));
std::cout << &test[0];
输出: foobar 有人可以解释为什么会这样
解决方案
流函数按值str
返回字符串。
这意味着这两个s.str()
调用将返回两个不同的字符串,并且它们各自的begin
和end
迭代器将用于不同的字符串,从而使std::copy
调用无效并导致未定义的行为。
推荐阅读
- asp.net-core - 抛出异常后循环返回的替代方法
- autodesk-forge - 如何在手机或平板电脑上访问模型三?
- java - 连接池连接不足。在 Jetty 嵌入式服务器中使用 DBCP2 BasicDataSource
- vb.net - 我在 Visual Basic -2015 中更新单个记录的完整代码,显示错误?
- docker - 如何为构建以运行 Spring Boot 应用程序的 Docker 映像配置 HTTPS 代理服务器?
- r - 使用 XML 包“Null”错误在 R 中进行 Webscraping
- reactjs - 在 React 和 Gatsby 中按 className 选择 dom 元素的正确方法
- javascript - 在 Github 页面上部署 Angular Universal?
- docusignapi - 如何在具有不同路由顺序的docusign API中添加相同的收件人?
- python - 为什么总是显示最稀有的输出?(Python 3)