yan*_*pas 1 c++ string iteration operator-overloading
我重载operator*了std::string类,但在这种情况下:
std::string operator*(std::string a, unsigned b) //bad
{
unsigned old_length = a.length();
a.resize(a.length()*b);
for(unsigned i = old_length ;i<a.length()*b; i++)
a[i]=a[i%old_length];
return a;
}
Run Code Online (Sandbox Code Playgroud)
程序崩溃并出现错误:
***"./ program"中的错误:free():下一个大小无效(快):0x0000000000cd20b0***已中止
如果我像这样重载它 - 没有错误:
std::string operator*(std::string a, unsigned b)
{
unsigned old_length = a.length();
std::string a2 = a;
a2.resize(a.length()*b);
for(unsigned i = 0 ;i<a.length()*b; i++)
a2[i]=a[i%old_length];
return a2;
}
Run Code Online (Sandbox Code Playgroud)
那问题出在哪里?有没有办法不创建新的字符串a2?它消耗额外的内存.
#include <iostream>
#include <string>
std::string operator*(unsigned b, std::string a)
{
return operator*(a, b);
}
int main(int argc, char **argv)
{
std::string a = "abcdef "; // if string contains more than 4 symbols - free error for the first case
std::string aaaa = 4*a;
std::cout << a << "\n"
<< aaaa << "\n"
<< std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
你不能a.length() * b再次迭代(因为它相当于old_length * b * b调整大小后).
条件必须是i < a.length()或i < old_length * b.
但为什么不使用一些std::string功能呢?
std::string operator*(std::string a, unsigned b)
{
a.reserve(a.length() * b);
for(unsigned i = 1 ; i <= b; i++)
a += a.substr(0, a.length() / b);
return a;
}
Run Code Online (Sandbox Code Playgroud)
我们还有效地消除了old_length变量(在性能方面不那么有效,请参阅下面的评论中更好的方法).
| 归档时间: |
|
| 查看次数: |
59 次 |
| 最近记录: |