Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm interpreting your code as follows. You have a <strong>struct</strong> named Vector with 3 members</p> <pre><code>struct Vector { double fieldA; double fieldB; double fieldC; } </code></pre> <p>The code below works as follows. It uses <code>std::find_if_not</code> with <strong>reverse iterators</strong> (<code>rbegin()</code> and <code>rend()</code>) to find the first element from the back that has a <code>fieldA</code> different from <code>0</code>. It then converts this to a regular iterator (using <code>base()</code>) and compares it to the end of the vector. Finally the call <code>v.erase</code> will actually erase them (the so-called <strong>erase-remove idiom</strong>)</p> <pre><code>#include &lt;algorithm&gt; #include &lt;vector&gt; #include &lt;iostream&gt; #include &lt;iterator&gt; int main() { struct Vector { int fieldA; int fieldB; }; std::vector&lt;Vector&gt; v = { Vector{ 1, 0 }, Vector{ 2, 1 }, Vector{ 0, 2 }, Vector{ 1, 3 }, Vector{ 0, 4 }, Vector{ 0, 5 }, Vector{ 5, 6 }, Vector{ 6, 7 }, Vector{ 0, 8 }, Vector{ 0, 9 }, Vector{ 0, 10} }; for (auto&amp; e: v) { std::cout &lt;&lt; "{" &lt;&lt; e.fieldA &lt;&lt; "," &lt;&lt; e.fieldB &lt;&lt; "}, "; }; std::cout &lt;&lt; "\n"; auto m = std::find_if_not(v.rbegin(), v.rend(), [&amp;](Vector const&amp; elem){ return elem.fieldA == 0; }).base(); if (m != v.end()) // remove all but one matching element v.erase(m + 1, v.end()); for (auto&amp; e: v) { std::cout &lt;&lt; "{" &lt;&lt; e.fieldA &lt;&lt; "," &lt;&lt; e.fieldB &lt;&lt; "}, "; }; std::cout &lt;&lt; "\n"; } </code></pre> <p>Output on <a href="http://liveworkspace.org/code/M8iTg%2414" rel="nofollow">LiveWorkSpace</a></p>
 

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