2016-04-18 9 views
1

std :: multiset内の要素の異なる発生をカウントするコードを探しています。私は決して停止ないと私は理由を知りません上記のforループのコードstd :: multisetと上限と下限の奇妙な振る舞い

#include <set> 
#include <iostream> 
#include <thread> 
#include <chrono> 

struct test 
{ 
    std::pair<std::string,std::string> p; 
    std::pair<unsigned short, unsigned short> s; 
    unsigned short c; 
}; 

bool operator<(test const & l, test const & r) 
{ 
    return (l.p < r.p || l.s < r.s); 
} 

int main(int argc, char ** argv) 
{ 
    test a = { {"p0","q0"} , {2,4} , 13 }; 
    test b = { {"p0","q0"} , {2,4} , 26 }; 
    test c = { {"p0","q0"} , {2,4} , 14 }; 
    test d = { {"p0","q0"} , {3,5} , 23 }; 
    //test e = { {"p0","q0"} , {3,5} , 22 }; 
    test f = { {"p1","q0"} , {2,4} , 13 }; 

    std::multiset<test> set; 
    set.insert(a); 
    set.insert(b); 
    set.insert(c); 
    set.insert(d); 
    //set.insert(e); 
    set.insert(f); 

    for(auto i=set.begin(); i!=set.end(); i=set.upper_bound(*i)) 
    { 
     std::this_thread::sleep_for(std::chrono::seconds(1)); 
     std::cout << set.count(*i) << std::endl; 
    } 
} 

ザ・を次しています。私が(で「e」を置く)上記のコードからコメントを削除した場合、出力は私が

3 
0 
2 

のような出力が得られ、この場合、ループ終了のために、私はどちらか理解できない

3 
1 
1 
1 
1 
... with endless output of "1" 

です。

+2

あなたの '演算子'は厳密な弱い順序の要件を満たしていません。 – milleniumbug

+1

私は、あなたの 'bool operator <(test const&l、test const&r)'は、[Compare concept](http://en.cppreference.com/w/cpp/concept/Compare)を満たしていないと思います'std :: multiset'の' Key'のためのものです。 – akakatak

+0

実際、演算子は<間違っていました。 – user1587451

答えて

0

上記のコメントは私に解決方法を指示しました。オペレータは間違っていた。

bool operator<(test const & l, test const & r) 
{ 
    if (l.p < r.p) 
    { 
     return true; 
    } 
    if (l.p == r.p && l.s < r.s) 
    { 
     return true; 
    } 
    return false; 
}