vector의 이분 검색 알고리즘
8677 단어 vector
#include <iostream>
#include <vector>
#include <string>
#include "base/tools.hpp"
using namespace std;
class Test
{
public:
int id;
string name;
public:
Test(int _id,string _name)
{
id = _id;
name = _name;
}
};
int get(int key,vector<Test>::iterator begin_it,vector<Test>::iterator end_it,vector<Test>::iterator & it)
{
end_it -= 1;
vector<Test>::iterator mid_it = begin_it + (end_it-begin_it)/2;
int count = 0;
while(begin_it <= end_it)
{
count++;
if(mid_it->id == key)
{
it=mid_it;
cout<<"total search count:"<<count<<endl;
return true;
}
else
{
if(mid_it->id < key)
{
begin_it = mid_it + 1;
}
else
{
end_it = mid_it - 1;
}
}
mid_it = begin_it + (end_it - begin_it)/2;
}
it = end_it;
return false;
}
template<typename T> bool get2(int key,T begin_it,T end_it,T & it)
{
end_it -= 1;
//typename vector<T>::iterator mid_it = begin_it + (end_it-begin_it)/2;
T mid_it = begin_it + (end_it-begin_it)/2;
int count = 0;
while(begin_it <= end_it)
{
count++;
if(mid_it->id == key)
{
it=mid_it;
cout<<"total search count:"<<count<<endl;
return true;
}
else
{
if(mid_it->id < key)
{
begin_it = mid_it + 1;
}
else
{
end_it = mid_it - 1;
}
}
mid_it = begin_it + (end_it - begin_it)/2;
}
it = end_it;
return false;
}
int main()
{
vector<Test> vect;
for(int i = 0;i<10000000;i++)
{
Test test(i,int_to_str(i));
vect.push_back(test);
}
//sort(vect.begin(),vect.end());
cout<<"vector has builded!"<<endl;
clock_t start,finish;
start = clock();
/*
vector<Test>::iterator it = vect.begin();
while(it!=vect.end())
{
if(it->id == 9999999)
{
cout<<"id:"<<it->id<<"\tname:"<<it->name<<endl;
break;
}
it++;
}
*/
vector<Test>::iterator it;
if(get(99999,vect.begin(),vect.end(),it))
{
cout<<"id:"<<it->id<<"\tit->name:"<<it->name<<endl;
}
else
{
cout<<"not found!"<<endl;
}
finish = clock();
cout<<" (s):"<<(double)(finish-start)/CLOCKS_PER_SEC<<"
";
}
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
자료구조_벡터(vector) in C++num_arr1 : 가장 기본적인 형태의 vector 선언이다. num_arr2 : vector의 크기를 정함과 동시에 선언한다. num_arr3 : vector의 크기를 정하면서, 해당 vector의 값을 무엇으로...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.