Hi,

I want to replace the numbers which are less than 5 in a container. So i write a code as follows. But it is not working. Please get me the solution for this. Destination container should be V2 itself. Where we have to specify destination container.

replace_if(V2.begin(),V2.end(),               //range
                   bind2nd(less<int>() ,5));          //replace criterion

Dani AI

Generated

As pointed out, the problem was not the iterator range but the missing "replacement value" argument: std::replace_if replaces matching elements in-place and needs a value to assign to those elements. For clearer, modern code prefer a lambda predicate instead of the old binder.

Here are two concise alternatives (do not re-run the original binder-based call shown earlier).

std::replace_if(V2.begin(), V2.end(),
                [](int x) { return x < 5; },
                0);

If the goal is to produce a separate destination container instead of modifying V2, use std::transform to write into an output container:

std::transform(V2.begin(), V2.end(), out.begin(),
               [](int x) { return x < 5 ? 0 : x; });

Notes and troubleshooting:

  • bind2nd and the old binder adapters are deprecated/removed in modern C++; prefer lambdas or std::bind ().
  • std::replace_if works in-place (no output iterator). If a separate destination is required, choose std::transform. See the standard docs for details: std::replace_if and std::transform.
  • If compilation fails with lambdas, enable a C++11-or-later mode on the compiler.

Recommended Answers

All 2 Replies

Hi,

I want to replace the numbers which are less than 5 in a container.
[...]

replace_if(V2.begin(),V2.end(),  bind2nd(less<int>() ,5));          //replace criterion

Replace them with what? You're missing the last parameter for the replace_if() function. If you want to replace them with '1' for example, you should use replace_if(V2.begin(),V2.end(), bind2nd(less<int>() ,5),1); and did you remember to

#include <algorithm>
#include <functional>

?

Replace them with what? You're missing the last parameter for the replace_if() function. If you want to replace them with '1' for example, you should use replace_if(V2.begin(),V2.end(), bind2nd(less<int>() ,5),1); and did you remember to

#include <algorithm>
#include <functional>

?

Thanks , I got it. I was missed last parameter.

replace_if(V2.begin(),V2.end(),               //range
                   bind2nd(less<int>() ,5),0);          //replace criterion

Now its working.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.