在vector中查找元素及其位置
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
// A dynamic array of integers
vector <int> vecIntegerArray;
//Insert sample integers into the array
vecIntegerArray.push_back(50);
vecIntegerArray.push_back(2991);
vecIntegerArray.push_back(23);
vecIntegerArray.push_back(9999);
cout << "The contents of the vector are:" << endl;
//Walk the vector and read values using an interator
vector <int>::iterator iArrayWalker = vecIntegerArray.begin();
//聲明迭代器對象iArrayWalker,並將其初始化爲指向容器開頭,即vector的成員函數begin()返回的值。
while (iArrayWalker != vecIntegerArray.end())
{
//Write the value to the screen
cout << *iArrayWalker << endl;
//Increment the iterator to access the next element
++iArrayWalker;
}
//Find an element(say 2991)in the array using the 'find' algorithm...
**vector <int>::iterator iElement = find(vecIntegerArray.begin(), vecIntegerArray.end(), 2991);**
//find操作的結果也是一個迭代器,通過將迭代器與容器末尾進行比較,可判斷find是否成功
//Check if value was found
if (iElement != vecIntegerArray.end())
{
//Value was found...Determine position int array;
int nPosition = distance(vecIntegerArray.begin(), iElement);
//distance計算找到的元素的所處位置的偏移量。
cout << "Value " << *iElement;
cout << " found in the vector at position:" << nPosition << endl;
}
getchar();
return 0;
}