C++ replace_if在 STL 中带有结构的向量上

C++ replace_if on vector with struct in STL

本文关键字:结构 向量 replace if STL C++      更新时间:2023-10-16

我一直在寻找一种使用 std::replace_if 更新向量中当前结构的方法,而不是创建新对象。

例如

std::vector<setting> settings;
// ... add stuff to settings
setting newsetting;     
std::string name = "something";
std::replace_if(settings.begin(), settings.end(), [&](setting const& v)
{
    return v.name == name;
}, newsetting);

在这种情况下,我需要使用 newset,有什么方法可以引用我现有的向量并更新其中的值?我已经查找了这个问题,但只在 boost 中找到了解决方案,我想严格在 STL 中执行此操作。

谢谢。

在我看来,

你不需要比花园品种范围迭代更花哨的东西:

std::vector<setting> settings;
for (auto &one_setting:settings)
{
    if (one_setting.name == name)
    {
         one_setting.a_method_that_changes_this_setting_somehow();
    }
}