c++ - std::string::insert 不适用于 to_string()。CPP
问题描述
我正在编写一个代码来在字符串的索引处插入一个整数,但是在提供要添加为字符串的整数之后,插入函数没有给出正确的输出。
它给出的错误是:
没有匹配的成员函数来调用插入字符串
这是我的代码:
#include <iostream>
using namespace std;
int main()
{
string s = "45564528";
int x = 8;
s.insert(s.begin()+5,to_string(x));
cout<<s<<endl;
return 0;
}
预期输出为 455648528。
解决方案
查看文档表明std::string::insert()
它需要 achar
或迭代器范围,而不是 a std::string
,它std::to_string()
自然会返回。至少,对于第一个参数采用迭代器的重载就是这种情况。
#include <iostream>
#include <string> // CHANGED: Include what you use
// using namespace std; // CHANGED: Bad practice
int main()
{
std::string s = "45564528";
int x = 8;
// CHANGED: Create string from the int, and use the iterator range overload
// to account for multi-digit numbers
auto tmp = std::to_string(x);
s.insert(s.begin()+5, tmp.begin(), tmp.end());
std::cout << s << '\n'; // CHANGED: std::endl is rarely actually needed
return 0;
}
有一个重载可以让你插入另一个std::string
,但第一个参数必须是索引而不是迭代器。所以这也可以:
#include <iostream>
#include <string>
int main()
{
std::string s = "45564528";
int x = 8;
s.insert(5, std::to_string(x));
std::cout << s << '\n';
return 0;
}
推荐阅读
- r - 逐行扩展并更宽地旋转
- python - 如何提高性能以从这个 Pandas 数据框中收集我需要的信息?
- excel - 在 MS Excel 中使用 IF AND 运算符会导致参数错误
- mysql - 将熊猫数据框添加到 MySQL
- java - Java Streams:使用 Collectors.toCollection 将返回集合修改为自定义类型
- javascript - 围绕inkscape旋转SVG组g:Javascript / Jquery中的transform-center-x / y
- go - 在 Go 程序中支持多个版本的 Kuberentes API
- javascript - VUE JS 将当前站点 url 附加到 href 的动态绑定中。如何只绑定字符串而不附加在当前 URL 中?
- r - 过去有特定 # 次观察的上个月值的持续时间
- git - 如何在 Git 重置选项之间进行选择