为了简化程序的开发,C++在基本库的基础上又提供了两种对象库,一种是string库,专门用于处理可变长的字符串对象;另一种是vector,作为一个容器可以容纳其他的对象。上述两种库对象都是连续存放的内存模式。
关于string:
1. 使用string库时当然要加入头文件:#include <string>,当然命名空间要声明为std;
2. 初始化方式:string s1; //默认构造函数,s1为空串
string s1("Hello");
string s2(s1);
string s1(n, 'c'); //将s1初始化为'c'的n个副本
3. s1.size()函数返回s1中的字符个数;s1.empty()用来确认字符串是否为空;
4. 读入字符串:一种是直接从标准输入读入:cin >> s1; //以空白字符(空格、换行、制表符)为分界,从第一个非空白字符读入,再遇空白字符 //终止
另一种则是按行读入:getline(cin, s1); //仅仅不读换行符,并且以换行符为分界,开头的空格也会读入
5. 为了避免出错,使用string类类型定义的配套类型string::size_type来表示涉及元素个数的变量和处理
6. string类对象可以拼接,类似于python,但是要求"+"两边必须至少有一个是string类对象
string类库的基本操作:
对象初始化;
基本属性:size和empty;
操作:添加新元素和访问成员
特有操作:对象拼接
- #include <iostream>
- #include <string>
-
- using namespace std;
-
- int main()
- {
- string str("Hello\n"); //字面值常量初始化法将'\n'作为一个换行符计算
- string::size_type size; //涉及到string长度/下标的变量必须使用string::size_type类型
- cout << "str's size is :"
- << (size = str.size())<< endl;
- cout << "str is :"
- <<str;
- cout <<"Initial test End..."<< endl;
- cout <<endl<<endl<<endl;
- cout <<"A new test..."<< endl;
-
- cout <<"Please input three strings:..."<<endl;
- string str1, str2, str3;
- cin >> str1;
- cin >> str2;
- cin >> str3;
- cout << "str1 + str2+ str3 :"
- <<(str = str1 + str2 +str3)<<endl;
- cout << "Now let's format the string..."<<endl;
- cout <<str1 + " " + str2 + " " + str3 //string类型拼接符"+"必须与一个string类型相邻
- <<endl; //string::"+"返回一个string类型对象所以 string + " " + "haha" is OK too
- //cout << "hello" + " "; 这样写会报错,"+"两侧没有string类型对象
- //即:string::"+"两侧不能都是字符串常量!
- system("pause");
- return 0;
- }
关于vector
1. vector是一个类模板,必须使用<>明确类型才成为一个具体的类类型,初始化同样有四种方式:
vector<T> v1; //默认构造函数v1为空
vector<T> v2(v1);
vector<T> v3(n, i); //包含n个值为i的元素
vetor<T> v4(n); //包含有值初始化元素的n个副本
2. vector的属性操作:vector.size()和vector.empty(),当然长度/个数是vector对应的配套类型:vector<T>::size_type
3. 访问vector元素可以借助于下标(同string),但是为了与其他容器一致起来(并非所有容器都可以使用下标访问成员),我们建议使用迭代器来访问成员。定义
vector<T> vec
vector<T> iterator iter = vec.begin(); //初始化一个迭代器指向vec的第一个元素
//当vector为空时,vec.begin() == vec.end()
*iter == vec[0]; //可以使用*iter来访问成员,iter++即可向后访问
4. vector对象只能用push_back()在后端添加成员,“=”仅仅用来为元素赋值
- #include <iostream>
- #include <vector>
-
- using namespace std;
-
- int main()
- {
- int num;
- vector<int> vec;
- while(cin >> num)
- {
- vec.push_back(num); //必须使用push_back()动态添加新元素
- }
- vector<int>::size_type size = vec.size();
- cout << "vector's length is :" << size<<endl;
- int sum = 0;
- //试用下标来访问vector中元素
- for (vector<int>::size_type index = 0; index != size; index++)
- {
- cout << "The " <<index <<" element is " << vec[index]<<endl;
- sum += vec[index];
- }
- cout << "The sum of integer is: "<< sum<<endl;
- //迭代器版本
- sum = 0;
- vector<int>::iterator iter = vec.begin();
- for (vector<int>::size_type index = 0; iter != vec.end(); iter++)
- {
- cout <<" The"<<index <<" element is "<< *iter<<endl;
- sum += *iter;
- }
- cout << "The sum of integer is: "<< sum<<endl;
-
- system("pause");
- return 0;
-
- }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。