LindaK
LindaK

Reputation: 21

C++ searching for one string in a set of pairs of strings

I have defined edges in my graph as a pair of cities, like: make_pair(city1, city2)

I have stored the pairs in a set<pair<string,string>>

I now want to change all instances of cityA to cityB. cityA could be in either the pair.first or pair.second position.

I have tried to search with following loops, but I get an error on the = sign, the assignment operator.

This code shows two ways.

What am I doing wrong?

for (edgeSetIter = edgeSet.begin(); edgeSetIter != edgeSet.end(); edgeSetIter++)            
    {
    if ((*edgeSetIter).first == cityA) { edgeSetIter->first = cityB; }
    else if ((*edgeSetIter).second == cityA) { (*edgeSetIter).second = cityB; }
    }                                                                                   

Upvotes: 2

Views: 82

Answers (1)

Jonathan Mee
Jonathan Mee

Reputation: 38969

You cannot modify elements of a set as they are the Key to the associative container. Exact quote from cplusplus.com:

In a set, the value of an element also identifies it (the value is itself the key, of type T), and each value must be unique. The value of the elements in a set cannot be modified once in the container (the elements are always const), but they can be inserted or removed from the container.

An alternative to a set may be using a non-associative container and: unique.

Upvotes: 1

Related Questions