赞
踩
- //例1.拼接字符串
-
- #include<iostream>
- using namespace std;
-
- int main()
- {
- string s1 = "Hello ";
- string s2 = "World! ";
- string s3 = " China";
- string s4;
-
- //第一种方式:append
- s4.append(s1);
- cout << s4.c_str() << endl;
- s4.append(s2);
- cout << s4.c_str() << endl;
- s4.append(s3);
- cout << s4.c_str() << endl;
-
- //第二种方式:+
- s4 += " welcome!";
- cout << s4 << endl;
- s4 = s4 + "libin";
- cout << s4 << endl;
- }
-
-
-
- //例2.使用str += "a", str = str + "a" 效率差距:
- /*
- str = str + "a"加的运算产生的是一个新的对象,再把结果返回,
- 而str += "a" 涉及到的应该是对象的引用,操作之后直接返回引用,
- 避免了产生新的对象。因此,两者的性能有一定的差距。
- */
-
- #include <iostream>
- #include <string>
- #include<time.h>
- using namespace std;
-
- int main()
- {
- static int num = 500000;
- time_t timeBegin, timeEnd;
- //开始
- timeBegin = time(NULL);
- string str = "";
- for (int i = 0; i < num; i++)
- {
- str = str + "a";
- }
- timeEnd = time(NULL);
- cout << "str=str +a所耗费的时间:" << timeEnd - timeBegin << " ms" << endl;
-
- //开始
- timeBegin = time(NULL);
- string str1 = "";
- for (int i = 0; i < num; i++)
- {
- str1 += "a";
- }
- timeEnd = time(NULL);
- cout << "str+=a所耗费的时间:" << timeEnd - timeBegin << " ms" << endl;
-
- return 0;
- }
-
- //输出结果
- /*
- str=str +a所耗费的时间:11 ms
- str+=a所耗费的时间:0 ms
- */
-

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。