代码之家  ›  专栏  ›  技术社区  ›  P.Musiał

使用条件语句迭代多重映射

  •  2
  • P.Musiał  · 技术社区  · 9 年前

    C++98/03

    我从第二个元素开始迭代多重映射:

    multimap<pair<string, string>, pair<string, int> >::iterator it = paths.begin();
    it++;
    

    for(; it != paths.end(); it++) {
        if((*it).first.first == (*it--).first.first ) {
            it++;
            cout << (*it).first.first << " ";
            cout << (*it--).first.first << endl;
            it++;
        }
        else {
            it++;
        }
    }
    

    我的问题是,如何使用迭代器的副本,而不是在每次(*it--)之后将其加回去?

    2 回复  |  直到 9 年前
        1
  •  4
  •   Vittorio Romeo    9 年前

    创建一个类似C++11的实用程序 std::prev :

    #include <algorithm>
    
    template <class T>
    T prev(T it)
    {
        std::advance(it, -1);
        return it;
    }
    

    for(; it != paths.end(); it++) {
        if((*it).first.first == prev(it)->first.first ) {
            cout << (*it).first.first << " ";
            cout << prev(it)->first.first << endl;
        }
        else {
            it++;
        }
    }
    
        2
  •  3
  •   Slava    9 年前

    只需使用另一个迭代器:

     typedef multimap<pair<string, string>, pair<string, int> >::iterator iterator;
     for( iterator it = paths.begin(); it != paths.end(); ) {
         iterator prev = it++;
         if( it == paths.end() )
             break;
         if( prev->first.first == it->first.first ) {
             // output here
         }
     }
    

    注意,您的代码不正确,首先它有UB作为 ==

     iterator it1 = it;
     if((*it1).first.first == (*it--).first.first ) { // not UB anymore, but result is always true as you compare the same element