vector或者list内部保存结构体或者对象时,可以实现和map一样的效果,但是千万不要手动遍历容器,这样会导致程序的性能下降数倍,最好的方法是使用std::find或者std::find_if来查找,速度快的多!
代码如下:
1、std::find例子
#include <iostream>
#include <vector>
using namespace std;
struct stMyTest
{
int nID;
int nData;
stMyTest(int id, int data) :nID(id), nData(data) {}
bool operator == (const stMyTest& t1)
{
return t1.nID == nID && t1.nData == nData;
}
};
int main()
{
vector<stMyTest> v;
for (int i = 0; i < 100; ++i)
{
v.emplace_back(i, i + 1);
}
auto it = std::find(v.begin(), v.end(), stMyTest(50, 51));
if (it != v.end())
cout << it->nID << " " << it->nData << endl;
return 0;
}
关键就在于重载自定义类的==运算符。
输出结果:
2、std::find_if的例子
需要引用algorithm
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
struct stMyTest
{
int nID;
int nData;
stMyTest(int id, int data) :nID(id), nData(data) {}
};
struct stFindID
{
int nFindID;
stFindID(int findID) :nFindID(findID) {}
bool operator()(const stMyTest&t1)
{
return t1.nID == nFindID;
}
};
int main()
{
vector<stMyTest> v;
for (int i = 0; i < 100; ++i)
{
v.emplace_back(i, i + 1);
}
auto it = std::find_if(v.begin(), v.end(), stFindID(50));
if (it != v.end())
cout << it->nID << " " << it->nData << endl;
return 0;
}
关键就在于需要一个仿函数来查找满足条件的值。
打印结果: