获取顺序容器vector,deque,string和array的首尾元素的方法有四个
生活随笔
收集整理的這篇文章主要介紹了
获取顺序容器vector,deque,string和array的首尾元素的方法有四个
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?獲取順序容器vector,deque,string和array的首尾元素的方法有四個:
(1)迭代器
(2)下標
(3)front() 和 back()成員函數
(4)at()成員函數
如下所示,得到首尾元素都有4個方法。
#include <iostream> #include <string> #include <vector> #include <deque> #include <list> #include <forward_list> #include <string> #include <array>using namespace std;#define LENGTH 10 typedef int TYPE; typedef vector<TYPE> VECTORTYPE; typedef deque<TYPE> DEQUETYPE; typedef list<TYPE> LISTTYPE; typedef forward_list<TYPE> FORWARD_LISTTYPE; typedef array<TYPE,LENGTH> ARRAYTYPE; void print(VECTORTYPE & ); void print(DEQUETYPE & ); void print(LISTTYPE & ); void print(FORWARD_LISTTYPE & ); void print(ARRAYTYPE & ); void print(string &); void pluralize(size_t ,string &); void print(list<string> &); void print(vector<string> &); int main() {vector<int> v_int{1,2,3,4};int val1 = v_int.at(0),val11 =v_int.front(),val12 = v_int[0],val13 = *v_int.begin();int val2 = *(v_int.end() -1),val21 = v_int.back(),val22 = v_int[v_int.size() - 1],val23 = v_int.at(v_int.size() - 1);cout << val1 << val11 << val12 << val13 << endl;cout << val2 << val21 << val22 << val23 << endl;return 0; }注意:如果越界(迭代器,下標,front(),back(),at()),編譯的時候會全部通過,但是運行時候會發生錯誤。at()會拋出運行時候異常,其余運行直接錯誤。
總結
以上是生活随笔為你收集整理的获取顺序容器vector,deque,string和array的首尾元素的方法有四个的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 顺序容器的访问:访问成员函数的返回是引用
- 下一篇: mysql中查询触发器的语句