C++:vector的begin()& end()&front()&back()&find()

1.begin函數

函數原型:

iterator begin();

const_iterator begin();

功能:返回一個當前vector容器中起始元素的迭代器

2.end函數

函數原型:

iterator end();

const_iterator end();

功能:返回一個當前vector容器中末尾元素的迭代器

3.front函數

函數原型:

reference front();

const_reference front();

功能:返回當前vector容器中起始元素的引用。

4.back函數

函數原型:

reference back();

const_reference back();

功能:返回當前vector容器中末尾元素的引用。

5.find函數

不同於map(map有find方法),vector本身是沒有find這一方法,其find是依靠algorithm來實現的。

在vector容器中查找6的數字.

#include <iostream>
#include <algorithm>
#include <vector>

int main()
{
    using namespace std;

    vector<int> vec;

    vec.push_back(1);
    vec.push_back(2);
    vec.push_back(3);
    vec.push_back(4);
    vec.push_back(5);
    vec.push_back(6);

    vector<int>::iterator it = find(vec.begin(), vec.end(), 6);

    if (it != vec.end())
        cout<<*it<<endl;
    else
        cout<<"can not find"<<endl;

    return 0;
}

記着要包含algorithm這一頭文件,其定義了find這一函數

建議大家還是自己手動敲一下。

以後不用再自己遍歷,直接調用此函數就可以了.

 

6.示例:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<char> v1;
    v1.push_back('m');
    v1.push_back('n');
    v1.push_back('o');
    v1.push_back('p');

    cout << "v1.front() = " << v1.front() << endl;
    cout << "v1.back() = " << v1.back() << endl;


    vector<char>::iterator iter1;
    vector<char>::iterator iter2;
    iter1 = v1.begin();
    cout << *iter1 << endl;
    //注意v1.end()指向的是最後一個元素的下一個位置,
    // 所以訪問最後一個元素的正確操作爲:v1.end() - 1;
    iter2 = v1.end()-1;
    cout << *iter2 << endl;
    return 0;
}

參考:

1.https://blog.csdn.net/weixin_40311211/article/details/81065786

2.https://blog.csdn.net/huangyimin/article/details/6133650

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章