一、vector 1.判断某元素是否存在 vector<string> vStr; int nRet = std::count(vStr.begin(), vStr.end(), "xiaochun" ); //判断vector中是否有 "xiaochun" 这个元素 2.查找某个元素 方法一: 自己写循环遍历 方法二: vector<string> vec; vector<string>::iterator iter; string gpcode= "SZ000001" ; iter = find(vec.begin(), vec.end(), gpcode); if (iter != vec.end()) { //vec中存在"SZ000001" } else { //没找到 } 注意: 如果vector中保存的是自定义类型(结构体/类),则需要为该类型重载==操作符。再用find #include <stdio.h> #include <vector> #include <string> #include <algorithm> //是C++的标准模版库(STL)中最重要的头文件之一,提供了大量基于迭代器的非成员模板函数。 class DemoStruct { public : string gpcode; int ymd; vector< int > vec; DemoStruct() { ymd = 20170707; gpcode = "" ; } bool operator == ( const DemoStruct & obj) const //重载 “==” 操作符,函数最后的 const 别忘了,否则会报错。(详见:http://www.cnblogs.com/SZxiaochun/p/7731900.html) { return ymd == obj.ymd && gpcode == obj.gpcode; //具体匹配条件,可以自己设定 } }; int main() { vector<DemoStruct> vec_struct; DemoStruct demo; demo.gpcode = "SZ000001" ; demo.ymd = 20170707; demo.vec.push_back(0); vec_struct.push_back(demo); DemoStruct tmpdemo; tmpdemo.gpcode = "SZ000001" ; tmpdemo.ymd = 20170707; vector<DemoStruct>::iterator iter; iter = find(vec_struct.begin(), vec_struct.end(), tmpdemo); if (iter != vec_struct.end()) { printf ( "%s" , "find it" ); } return 0; } 二、map 1.判断某元素是否存在 map< int , string> mapDemo; bool bRet = mapDemo.count(100); //判断mapDemo中是否有 key = 100 的元素 2.查找某个元素 map< int , string>::iterator iter = mapDemo.find(100); if (iter != m_Int.end()) { //找到了 } else { //没找到 }

浙公网安备 33010602011771号