C++ 在一组字符串对中搜索一个字符串

标签 c++ set std-pair

我在图表中将边定义为一对城市,例如: make_pair(city1, city2)

我已将这些对存储在 set<pair<string,string>>

我现在想更改 cityA 的所有实例至 cityB . cityA可以在 pair.first 中或 pair.second位置。

我尝试使用以下循环进行搜索,但在 = 符号(赋值运算符)上出现错误。

这段代码展示了两种方式。

我做错了什么?

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

最佳答案

您不能修改集合的元素,因为它们是关联容器的键。准确 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.

set 的替代方法可能是使用非关联容器和:unique .

关于C++ 在一组字符串对中搜索一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31867520/

相关文章:

python - 设置控制台宽度(Windows、Python)

c++ - 将 `std::unordered_map` 值放入 `std::pair`

c++ - 重构大型 C++ 类

c++ - boogle 中的段错误

rust - 获取 BTreeSet 的第一个成员

c++ - 按字符串对 std::vector<std::pair<std::string,bool>> 进行排序?

c++ - 初始化 std::pair<double, std::array<std::pair<double, double>, 3>>

c++ - 使用 clang 获取类中的方法列表

C++映射真的很慢吗?

scala - 减少一组空集是否有效?