Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to contain my class with std::set
    text
    copied!<p>I'm trying to write a program in C++ language.</p> <p>Class Edge indicates the connection between u and v.</p> <p>Edge a which indicates the connection between u and v. Edge a' which indicates the connection between v and u. Edge a and a' indicate same connection. So, I want to contain either a or a'.</p> <p>I know "set" stores unique elements. So I want to use this. I define operator&lt; below.</p> <p>When I search bugs, I found some trubles. I store (1,2) -> (1,2) -> (2,1) -> (3,2) -> (2,3) -> (5,2). </p> <p>But set stores</p> <pre><code>1 2 5 2 3 2 1 2 &lt;-- Why ???? </code></pre> <p>Could you help me??</p> <pre><code>#include&lt;iostream&gt; #include&lt;set&gt; class Edge { private: int u, v; public: bool operator&lt; (const Edge&amp; e) const { bool result = true; if( (u == e.u &amp;&amp; v == e.v) || (v == e.u &amp;&amp; u == e.v) ) { result = false; } return result; } std::pair&lt;int, int&gt; pair() const { return std::pair&lt;int, int&gt;(u, v); } Edge(int u_, int v_) : u(u_), v(v_) {} }; int main(void) { std::set&lt;Edge&gt; edge; std::set&lt;Edge&gt;::iterator eit; edge.insert(Edge(1,2)); // &lt;-- (1,2) can be contained. edge.insert(Edge(1,2)); // &lt;-- (1,2) doesn't have to be contained. edge.insert(Edge(2,1)); // &lt;-- (2,2) doesn't have to be contained. edge.insert(Edge(3,2)); // &lt;-- (3,2) can be contained. edge.insert(Edge(2,3)); // &lt;-- (2,3) doesn't have to be contained. edge.insert(Edge(5,2)); // &lt;-- (5,2) doesn't have to be contained. edge.insert(Edge(1,2)); // &lt;-- (1,2) doesn't have to be contained. But edge contains this. Why? for(eit = edge.begin(); eit != edge.end(); eit++) { std::cout &lt;&lt; (*eit).pair().first &lt;&lt; " " &lt;&lt; (*eit).pair().second &lt;&lt; std::endl; } return 0; } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload