반응형

다른 글들은 답답하게 상수값 넣고 int 배열의 인덱스값만 가져오는 쉬운 예시만 보여줘서 직접 글을 올립니다.

 

class Location {
private:
  int _allowMethod;
  bool _isAutoindex;

  string _cgiPath;
  string _uriPath;
  string _idxPath;
  string _rootPath;
  string _redirectPath;
  string _autoindexPath;

public:
  Location();
  Location(const Location &loc);
  Location(const LocationData &data);
  Location &operator=(const Location &loc);
  ~Location();

  void setMethods(int n);
  void setIsAutoindex(bool f);
  void setData(LocationData data);
  void setUriPath(string path);
  void setIdxPath(string path);
  void setCgiPath(string path);
  void setRootPath(string path);
  void setRedirectPath(string path);
  void setAutoindxPath(string path);

  int getMethods() const;
  bool getIsAutoindex() const;
  string getCgiPath() const;
  string getUriPath() const;
  string getIdxPath() const;
  string getRootPath() const;
  string getRedirectPath() const;
  string setAutoindxPath() const;
};

위와 같은 클래스가 있을 때

클래스를 STL로 관리한다 치고 어떤 멤버 변수가 특정 값을 갖고 있는 클래스만을 가져오고 싶다면?

 

값을 비교하는 boolean 함수가 필요합니다.

struct CompareValue {
    string _str;
    CompareValue(string str) : _str(str) {}
    bool operator()(const Location& loc) const {
        return !loc.getUriPath().compare(_str);
    }
};

Location Server::getLocation(string uri) const {
  vector<Location>::const_iterator ret = 
  		// 구조체 생성과 동시에 operator 호출
  		find_if(_locations.begin(), _locations.end(), CompareValue(uri)); 
  

  if (ret == _locations.end())
    return Location();
  return *ret;
}

Server라는 클래스는 Location을 vector 컨테이너로 관리하는 클래스입니다.

고유한 uri 문자열을 가지고 있는 특정 클래스만을 가져오는 Server::getLocation 함수입니다.

 

find_if는 첫 인자와 두 번째 인자 사이를 반복 순회하며 세 번째 인자를 비교값으로 삼는 함수입니다.

 

여기서 find_if의 세 번째 인자를 보시면 구조체 생성자가 있습니다.

CompareValue의 생성자를 넣고 있는데 find_if라는 함수의 괄호 속에 있기 때문에

생성과 동시에 operator()가 호출되고 인자로 들어온 iterator의 값을 인자로 넣어서 비교하게 됩니다.

 

따라서 함수의 인자인 uri가 "/naver.com" 이라는 값을 갖고 있으면

vector<Location> _locations를 순회해서 _locations.uri의 값이 "/naver.com"인 클래스를 찾게 됩니다.

 

references


https://stackoverflow.com/questions/6679096/using-find-if-on-a-vector-of-object

 

Using find_if on a vector of object

I have a vector of that looks like the following: class Foo { //whatever }; class MyClass { int myInt; vector<Foo> foo_v; }; And let's say, in the main: int main (void) { ...

stackoverflow.com

https://en.cppreference.com/w/cpp/algorithm/find

 

std::find, std::find_if, std::find_if_not - cppreference.com

(1) template< class InputIt, class T > InputIt find( InputIt first, InputIt last, const T& value ); (constexpr since C++20) (until C++26) template< class InputIt, class T = typename std::iterator_traits                                    

en.cppreference.com

 

반응형
원피스는 실존하다