Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is a good place to apply the remove/erase idiom:</p> <pre><code>accDetails.erase( std::remove_if( accDetails.begin(), accDetails.end(), [username](AccDetails const &amp;a) { return username == a.username; }), accDetails.end()); </code></pre> <p>As a bonus, this is likely to be a little bit faster than what you were doing (or maybe quite a bit faster, if your vector is large). Erasing each item individually ends up as O(N<sup>2</sup>), but this will be O(N), which can be pretty significant when/if N gets large.</p> <p>If you can't use C++11, the lambda won't work, so you'll need to encode that comparison separately:</p> <pre><code>class by_username { std::string u; public: by_username(std::string const &amp;u) : u(u) {} bool operator()(AccDetails const &amp;a) { return u == a.username; } }; accDetails.erase( std::remove_if(accDetails.begin(), accDetails.end(), by_username(username)), accDetails.end()); </code></pre> <p>Alternatively, you can overload <code>operator==</code> for your <code>AccDetails</code> class, and handle the comparison there. For example:</p> <pre><code>#include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;algorithm&gt; #include &lt;string&gt; #include &lt;iterator&gt; class AccDetail { std::string name; int other_stuff; public: AccDetail(std::string const &amp;a, int b) : name(a), other_stuff(b) {} bool operator==(std::string const &amp;b) { return name == b; } friend std::ostream &amp;operator&lt;&lt;(std::ostream &amp;os, AccDetail const &amp;a) { return os &lt;&lt; a.name &lt;&lt; ", " &lt;&lt; a.other_stuff; } }; int main(){ std::vector&lt;AccDetail&gt; ad = { {"Jerry", 1}, { "Joe", 2 }, { "Bill", 3 } }; std::cout &lt;&lt; "Before Erase:\n"; std::copy(ad.begin(), ad.end(), std::ostream_iterator&lt;AccDetail&gt;(std::cout, "\n")); ad.erase( std::remove(ad.begin(), ad.end(), "Joe"), ad.end()); std::cout &lt;&lt; "\nAfter Erasing Joe:\n"; std::copy(ad.begin(), ad.end(), std::ostream_iterator&lt;AccDetail&gt;(std::cout, "\n")); } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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