ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • stl 컨테이너 환형 순회
    프로그래밍/c++ 2018. 5. 23. 08:41
    반응형

    UI 프로그래밍을 담당하시는 하시는 분이 Form 안의 UI들을 환형으로 순회하는 걸 간단하게 표현하고 싶은데 어떻게 하면 심플하게 할 수 있을지 여쭤보셨다

    사용처는 컨테이너의 맨 끝 요소에 있는 상태에서 우측 방향키를 누르면 다시 처음 위치의 UI에 위치하도록 하는 게 목적이다.

    기존에 이미 작성된 코드가 있었기에 해당 부분을 별다른 변경 없이 사용할 수 있도록 값으로 회전할 수 있어야 했고,

    난 다음과 같은 코드를 만들어줬다.


    iterator로

    template < typename Container >
    inline typename Container::iterator
    GetNextIteratorCircular(const Container& container, typename Container::iterator currentIterator)
    {
      if (currentIterator == container.end())
      {
        return container.end();
      }
      auto next = ++currentIterator;
      return next == container.end() ? container.begin() : next;
    }


    value로

    template < typename Container >
    inline typename Container::value_type
    GetNextValueCircular(const Container& container, typename Container::const_reference value)
    {
      auto i = std::find(container.begin(), container.end(), value);
      if (i == container.end())
      {
        return *container.begin();
      }
      auto next = ++i;
      return next == container.end() ? *container.begin() : *next;
    }


    map도..

    template < typename KeyType, typename ValueType >
    inline ValueType
    GetNextValueCircular(const std::map<KeyType, ValueType>& container, const ValueType& value)
    {
      auto i = std::find_if(container.begin(), container.end(), [&](const auto& item) {
        return item.second == value;
      });
      if (i == container.end())
      {
        return (*container.begin()).second;
      }
      auto next = ++i;
      return next == container.end() ? (*container.begin()).second : (*next).second;
    }



    위 코드를 테스트 해보는 코드

    int main()

    {
    using namespace std;

    vector<int> vec{1,2,3};
    list<int> li{1,2,3};
    map<int,int> m{{1,1},{2,2},{3,3}};
    {// vector
    cout << "vector" << endl;
    auto j = 1;
    for(int i = 0; i != 4; ++i)
    {
    j = GetNextValueCircular(vec, j);
    cout << j << endl;
    }
    }
    {// list
    cout << "list" << endl;
    auto j = 1;
    for(int i = 0; i != 4; ++i)
    {
    j = GetNextValueCircular(li, j);
    cout << j << endl;
    }
    }
    {// map
    cout << "map" << endl;
    auto j = 1;
    for(int i = 0; i != 4; ++i)
    {
    j = GetNextValueCircular(m, j);
    cout << j << endl;
    }
    }
    return 0;
    }


    결과 

    output>>
    vector
    2
    3
    1
    2
    list
    2
    3
    1
    2
    map
    2
    3
    1
    2


    반응형
Designed by Tistory.