WillyB
WillyB

Reputation: 23

Search for and replace a value in a vector of structs

I am trying to compare a string to a struct element in a vector of structs and, if the values match, replace value in the struct element with a new value. I am able to populate the vector fine but I'm having issues getting the search and replace to work.

struct info {
    string name;
    string phone;
    string address;
}
vector<info> data;

At first I simply tried to loop through each element in the vector and compared the current value with the string. If they matched, I replaced the current value with the new value. This seemed to work, although the new value would revert back to the old one. I assume I'm changing a copy but I don't understand why. Here's the code.

for (auto e : data)
{
    if (e.name == old_name)  { e.name = new_name; }
}

My most recent attempt uses std::replace_if and a lambda expression to do the search and replace.

std::replace_if(data.begin(), data.end(), [old_name](info i){ return i.name == old_name; }, new_name);

However, the code doesn't compile and gives the following error - C2679 binary '=': no operator found which takes a right-hand operand of type 'const _Ty' (or there is no acceptable conversion)

Can anyone help me understand what's going on?

Upvotes: 0

Views: 1068

Answers (1)

cigien
cigien

Reputation: 60238

To change the elements in the vector, you need to take a reference in the range-for loop:

for (auto &e : data)

Otherwise you are making a copy, which doesn't change the original elements.

The 4th parameter of replace_if needs to take an info object, not just the new_name value.

Instead of replace_if, the appropriate algorithm to use here would be for_each, which modifies the info objects as needed:

std::for_each(data.begin(), data.end(), 
               [old_name, new_name](info &i) { 
                 if (i.name == old_name)
                    i.name = new_name;
              });

However, in this case, the range-for loop is probably less code, and easier to read and write.

Also, please avoid using namespace std;, it's bad practice.

Upvotes: 3

Related Questions