CC++ <deque> 容器

    科技2022-07-11  107

    deque

    下标操作迭代器操作两种访问越界出现的问题at越界访问[ ]越界访问 完善优化中。。。

    #include <iostream> #include <Windows.h> #include <deque> using namespace std; int main(int argc, char* argv[]) { deque<int> deqIntA, deqIntB, deqIntC, deqIntD; deqIntA.push_back(1); deqIntA.push_back(2); deqIntA.push_back(3); deqIntA.push_back(4); deqIntA.push_back(5); deqIntA.push_back(6); deqIntB.assign(deqIntA.begin(), deqIntA.end()); deqIntC.assign(4, 890); deqIntD = deqIntA; deqIntC.swap(deqIntD); //普通迭代器 cout << "普通迭代器:"; for (deque<int>::iterator it = deqIntC.begin(); it != deqIntC.end(); ++it) { cout << *it << " "; } for (deque<int>::iterator it = deqIntD.begin(); it != deqIntD.end(); ++it) { cout << *it << " "; } cout << endl; system("pause"); return 0; }

    下标操作

    at(int)访问容器里的元素 函数的作用是:返回一个对loc上的dequeue元素的引用。at()函数比[]操作符更安全,因为它不允许您引用dequeue边界之外的项。

    #include <iostream> #include <Windows.h> #include <deque> using namespace std; class student { public: student(int age) { cout << "默认构造函数" << endl; this->age = age; } student(const student& other) { cout << "拷贝构造函数" << endl; this->age = other.age; } ~student() { cout << "析构函数student" << endl; } int getAge() { return this->age; } private: int age; }; int main(int argc, char* argv[]) { deque<int> deqIntA; deque<float> deqFloat; deque<student> deqStu; deque<student*> deqStup; deqIntA.push_back(1); deqFloat.push_back(0.1f); deqStu.push_back(student(18)); deque<int> deqIntB(deqIntA.begin(), deqIntA.end()); deque<int> deqIntC(10, 0); deque<int> deqIntD(deqIntC); /*cout << "deqIntD中的元素:" << endl; for (unsigned int i = 0; i < deqIntD.size(); i++) { cout << deqIntD[i] << endl; }*/ deqIntA.push_back(1); deqIntA.push_back(2); deqIntA.push_back(3); deqIntA.push_back(4); deqIntA.push_back(5); deqIntA.push_back(6); deqIntA.push_back(7); deqIntA.pop_front(); deqIntA.pop_front(); deqIntA.push_front(7); deqIntA.push_front(8); deqIntA.pop_back(); cout << "deqIntA中的元素:" << endl; for (unsigned int i = 0; i < deqIntA.size(); i++) { cout << deqIntA[i] << endl; } system("pause"); return 0; }

    迭代器操作

    #include <iostream> #include <Windows.h> #include <deque> using namespace std; int main(int argc, char* argv[]) { deque<int> deqIntA; deqIntA.push_back(1); deqIntA.push_back(2); deqIntA.push_back(3); deqIntA.push_back(4); deqIntA.push_back(5); deqIntA.push_back(6); //普通迭代器 cout << "普通迭代器:"; for (deque<int>::iterator it = deqIntA.begin(); it != deqIntA.end(); ++it) { (*it)++; cout << *it << " "; } cout << endl; //常量迭代器 cout << "常量迭代器:"; deque<int>::const_iterator cit = deqIntA.cbegin(); for (; cit != deqIntA.cend(); ++cit) { cout << *cit << " "; } cout << endl; cout << "逆转迭代器:"; deque<int>::reverse_iterator rit = deqIntA.rbegin(); for (; rit != deqIntA.rend(); ++rit) { cout << *rit << " "; } }

    两种访问越界出现的问题

    at越界访问

    [ ]越界访问

    完善优化中。。。

    Processed: 0.009, SQL: 8