1. 程式人生 > >c++ 對vector中元素進行排序,查詢,返回下標的方法

c++ 對vector中元素進行排序,查詢,返回下標的方法

排序

對vector中的元素進行排序

使用標頭檔案algorithm中的sort可以對vector中的元素進行從小到大排序。使用方法為:

#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;
void main() {
    vector<int> temp = { 1,3,2,4,5,0 };
    sort(temp.begin(), temp.end());
    for (vector<int>::iterator i = temp.begin(); i != temp.end(); i++)
        cout
<< *i << endl; }

輸出結果為:
這裡寫圖片描述

自定義排序方法

使用sort的自定義排序方法:

#include<vector>
#include<algorithm>
#include<iostream>
using namespace std;

typedef struct NODE {
    int x;
    int y;
}node;
bool comp(node & a, node & b) {
    return a.x < b.x;//若前一個元素小於後一個元素,則返回真,否則返回假,即可自定義排序方式
} void main() { vector<node> temp; node a1, a2, a3; a1.x = 1; a1.y = 0; a2.x = 0; a2.y = 1; a3.x = 3; a3.y = 2; temp.push_back(a1); temp.push_back(a2); temp.push_back(a3); sort(temp.begin(), temp.end(),comp); for (vector<node>::iterator i = temp.begin(); i != temp.end(); i++) cout
<< (*i).x <<"*"<<(*i).y<< endl; }

輸出結果為:
這裡寫圖片描述

查詢指定元素,並返回迭代器

使用函式為find,使用方法為:

vector<int> temp = { 1,3,2,4,5,0 };
find(temp.begin(),temp.end(),value);//value為要查詢的值,該函式返回一個指向對應元素的迭代器

由迭代器得到元素下標

vector<int> temp = { 1,3,2,4,5,0 };
vector<int>::iterator it=temp.begin();
it+=2;
//此時it對應的元素下標為
int index=&*-&temp[0];