在公司用到一个奇怪的例子,就是vector里存放指针,指针指向一个vector,自己写了一个小demo,例子如下:
#include "iostream"
#include "algorithm"
#include "vector"
#include "memory"
#include "ctime"
using namespace std;
struct Ipvseg
{
Ipvseg(int i, int j) :start(i), end(j){}
int start;
int end;
};
bool InSegment(int ip, Ipvseg segment)
{
return ip >= segment.start&&ip <= segment.end;
}
struct Advwhite
{
Advwhite(vector<Ipvseg> Ipvsegs, vector<int> advids) :Ipvsegs_(Ipvsegs), advids_(advids){}
vector<Ipvseg> Ipvsegs_;
vector<int> advids_;
};
void query(int ip, vector<Advwhite>& advs, vector<vector<int>*> &result){
for (auto iter = advs.begin(); iter != advs.end(); ++iter) //iterΪAdvwhite
{
int left = 0;
int right = iter->Ipvsegs_.size()-1;
int flag = false;
while (left <= right){
int middle = (left + right) / 2;
if (InSegment(ip, iter->Ipvsegs_[middle])){
flag = true;
break;
}
if (ip < iter->Ipvsegs_[middle].start){
right = middle - 1;
}
else{
left = middle + 1;
}
}
if (flag){
result.push_back(&(iter->advids_));
}
}
}
int main(){
// clock_t start,end;
// start=clock();
Ipvseg ip1(3, 5);
Ipvseg ip2(8, 10);
Ipvseg ip3(15, 17);
Ipvseg ip4(21, 23);
Ipvseg ip5(25, 28);
Ipvseg ip6(30, 32);
vector<Ipvseg> Ipvsegs1 = { ip1, ip2, ip3 };
vector<Ipvseg> Ipvsegs2 = { ip4, ip5, ip6 };
vector<int> advids1 = { 132, 432, 543, 654, 765, 867 };
vector<int> advids2 = { 134, 435, 546, 65, 767, 863 };
Advwhite adw1(Ipvsegs1, advids1);
Advwhite adw2(Ipvsegs2, advids2);
vector<Advwhite> Advs = { adw1, adw2 };
vector<vector<int>*> result;
//vector<shared_ptr<vector<int>>> result;
query(30,Advs,result);
for (auto i : result)
{
for(auto j:(*i))
{
cout<<j<<" ";
}
cout<<endl;
}
// end=clock();
// double total=(double)((double)(end-start)/CLOCKS_PER_SEC);
// cout<<total<<endl;
}
后来把普通指针又换成了shared_ptr,用法相同。