본문 바로가기

Programming/C/C++

std::find 클래스 멤버로 찾기

function template

<algorithm>

std::find

template <class InputIterator, class T>
   InputIterator find (InputIterator first, InputIterator last, const T& val);
Find value in range
Returns an iterator to the first element in the range [first,last) that compares equal to val. If no such element is found, the function returns last.

The function uses operator== to compare the individual elements to val.

The behavior of this function template is equivalent to:
1
2
3
4
5
6
7
8
9
template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) {
    if (*first==val) return first;
    ++first;
  }
  return last;
}


STL의 find를 이용하여 vector<class>의 iterator를 반환한다.

이때, 클래스의 멤버로 찾고 싶다면, 다음과 같이 한다.

operator == 를 재정의 하여 해당 멤버로 비교할 수 있도록 함수를 추가하여 주면 된다.

bool operator==(const Test& t) { return (this->value == t.value); }




class Test

{

public:

Test() : value(0) {}

Test(int v) : value(v) {}

virtual ~Test() {}


public:

bool operator==(const Test& t) { return (this->value == t.value); }


public:

int value;

};



int main() {


std::vector<Test> t;

Test a(1);

Test b(2);

Test c(3);

t.push_back(a);

t.push_back(b);

t.push_back(c);


Test com(3);

std::vector<Test>::iterator it;

it = std::find(t.begin(), t.end(), com);

if ( t.end() != it )

{

printf("find = %d\n", (*it).value);

}


return 0;

}


'Programming > C/C++' 카테고리의 다른 글

ffmpeg tutorial  (0) 2016.05.13
gettimeofday를 대체하는 clock_gettime 함수  (0) 2014.12.22
c언어 매크로 사용법 - 1. #, ## 연산자  (0) 2014.12.05
HEX dump  (0) 2014.12.01
C Timer 만들어 사용하기.  (0) 2014.11.08