swap()
swap()接口表示交换,有以下两种编写方式
void test_string()
{
string s1("hello");
string s2("world");
cout << s1 << "--" << s2 << endl;
s1.swap(s2);//单纯地成员变量的交换,指针交换,代价小
cout << s1 << "--" << s2 << endl;
swap(s1, s2); //产生了一个临时对象,拷贝构造,再赋值,再赋值,代价大,效率低
cout << s1 << "--" << s2 << endl;
}
两种方法都可以实现交换,但是代价不一样,更倾向于使用s1.swap(s2)
replace()
replace()是string类中经常被使用的一个接口,功能是替换。下面以一个例子来说明。
void test_string1()
{