c++erase-remove-idiom

How can I adapt the erase-remove idiom to work with vector tuples?


I have a vector of tuples with members j, k, and l. I am trying to adapt the erase-remove idiom such that I can remove an entire tuple if the value of the .k member meets a certain condition.

I tried using the standard .erase(removeif()) methodology where the predicate referenced the tuple member position, but was told that the class of vector in question has no member "k".

vec_list_iter_exp_out.erase(
    std::remove_if(
        vec_list_iter_exp_out.begin(),
        vec_list_iter_exp_out.end(), 
        vec_list_iter_exp_out.k < 33), vec_list_iter_exp_out.end());

I would expect that if vec_list_iter_exp_out consisted of the following, hypothetical values:

vec_list_iter_exp_out[0] = 5, 22, 9
vec_list_iter_exp_out[1] = 12, 31, 54
vec_list_iter_exp_out[2] = 17, 42, 0
vec_list_iter_exp_out[3] = 253, 3, 5
vec_list_iter_exp_out[4] = 65, 110, 24

That the entirety of vec_list_iter_exp_out[2] and vec_list_iter_exp_out [4] would be removed and vec_list_iter_exp_out would then consist of the following:

vec_list_iter_exp_out[0] = 5, 22, 9
vec_list_iter_exp_out[1] = 12, 31, 54
vec_list_iter_exp_out[2] = 253, 3, 5

Instead I get the aforementioned compile error.

Any help would be greatly appreciated!

Edit: definition of the vector in question, as requested.

struct TriStore
{
    double j,k,l;
};

std::vector<TriStore> vec_list_iter_exp_out;

and snippet for insertion (obviously references other functions and what-have-you, but that would take up far too much space)

    for(int z = 1; z <= iters; z++)
    {
        vec_iters.push_back(vec_list_iter_exp_out.size());
        for(int i = vec_iters[z-1]; i < vec_iters[z]; i++)
        {
            if(vec_list_iter_exp_out[i].k < kk)
            {
                triangle_list(vec_list_iter_exp_out[i].j,vec_list_iter_exp_out[i].k,vec_list_iter_exp_out[i].l);
                vec_list_iter_exp_out.insert(vec_list_iter_exp_out.end(),vec_tri_list.begin(),vec_tri_list.end());
            }
        }
    }

Solution

  • Third argument of remove_if needs to be a unary predicate. Instead you are passing an expression.

    Instead of vec_list_iter_exp_out.k < 33 try something like [](const TriStore &x){return x.k < 33;}

    What if I want to decide this 33 at runtime

    From this comment by Nishant Singh: Please use

    [&value](const TriStore& x) {return x.k < value;}  // Capture by reference
    [value](const TriStore& x) {return x.k < value;}  // Capture by value
    

    p.s. Instead of TriStore why don't you use tuple<double, double, double>?