C++学习笔记(七)

本文详细介绍了C++中的array和vector容器,包括它们的初始化、元素访问、添加与删除元素的方法,以及容量和大小的管理。array是一个固定长度的序列,无法增加或删除元素,而vector的大小可以自动增长,支持高效地在末尾添加或删除元素。
摘要由CSDN通过智能技术生成

时间:2018/12/5
地点:元征总部
天气:骄阳似火


                                                                                                         笔记

1.basic_string和string类均提供了常规的迭代器和反向迭代器:
(1)可以使用迭代器遍历string内的所有字符,并且对这些字符进行排序、逆向重排、找出最大值等操作。对迭代器而言,如果
发生重新分配,或其所指的值发生某些变化时,迭代器会失效。
(2)string类中和使用迭代器相关的成员函数:begin()、end()、rbegin()、rend()、append()、assign()、insert()、erase()
、replace()等
(3)例子:

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main ()
{
    string s ("The zip code of Hondelage in Germany is 38108.");
    cout << "Original: " << s << endl;
    string sd(s.begin(),s.end ()); //构造函数中使用迭代器
    cout << "Destination: " << sd << endl;
    transform (sd.begin(), sd.end(), sd.begin(), toupper); //算法中使用迭代器(仿函数)
    cout << "Destination (All Toupper)): " << sd << endl;
    string sd1;
    sd1.append (sd.begin(),(sd.end() -7)); //append()函数中使用迭代器
    cout << "Destination sd1: " << sd1 << endl;
    string sd2;
    string::reverse_iterator iterA;
    string temp = "0";
    for (iterA = sd.rbegin (); iterA != sd.rend (); iterA++) //reverse_iterator
    {
        temp=* iterA;
        sd2.append (temp);
    }
    cout << "Destination sd2: " << sd2 << endl;
    sd2.erase (0, 15); //erase()函数中使用迭代器
    cout << "Destination sd2 (Erased 15 chars) : " << sd2 << endl;
    string::iterator iterB = sd2.begin ();
    string sd3 = string ("12345678");
    sd2.insert (sd2.begin(), sd3.begin(), sd3.end()); //insert()函数中使用迭代器
    cout << "Destination sd2 (Insert 8 chars) : " << sd2 << endl;
    sd2.replace (sd2.begin (), sd2.end(), "This is an Exarrple of Replace"); //Replace
    cout <<"Destination sd2 (Replace All): " << sd2 << endl; // replace ()函数中使用迭代器
}

输出:
Original: The zip code of Hondelage in Germany is 38108.
Destination: The zip code of Hondelage in Germany is 38108.
Destination (All Toupper)): THE ZIP CODE OF HONDELAGE IN GERMANY IS 38108.
Destination sd1: THE ZIP CODE OF HONDELAGE IN GERMANY IS
Destination sd2: .80183 SI YNAMREG NI EGALEDNOH FO EDOC PIZ EHT
Destination sd2 (Erased 15 chars) : EG NI EGALEDNOH FO EDOC PIZ EHT
Destination sd2 (Insert 8 chars) : 12345678EG NI EGALEDNOH FO EDOC PIZ EHT
Destination sd2 (Replace All): This is an Exarrple of Replace

2.序列容器以线性序列的方式存储元素,以下有5种标准的序列容器,每种容器都具有不同的特性:
(1)array<T,N> (数组容器) :是一个长度固定的序列,有 N 个 T 类型的对象,不能增加或删除元素。
(2)vector<T> (向量容器) :是一个长度可变的序列,用来存放T类型的对象。必要时,可以自动增加容量,但只能在序列的末
尾高效地增加或删除元素。
(3)deque<T> (双向队列容器) :是一个长度可变的、可以自动增长的序列,在序列的两端都能高效地增

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值