【问题标题】:Search both elements of a pair and replace either element搜索一对的两个元素并替换其中一个元素
【发布时间】:2021-01-10 03:55:50
【问题描述】:

给定一对整数p,我希望能够用3 替换其中的任何2,反之亦然,所以我做了这样的事情:

pair<int,int> f(pair<int, int> p) {

    if (p.first == 2)
        p.first = 3;
    else if (p.first == 3)
        p.first = 2;

    if (p.second == 2)
        p.second = 3;
    else if (p.second == 3)
        p.second = 2;

    return p;
}

但是,如果我想替换的不仅仅是这两个数字,一个一个一个一个,这个函数写起来会很烦人。对于这个例子,我怎样才能做到这一点,而不需要编写四个 if 语句,或者使用更少的代码,以便它可以扩展到更多可能需要替换的数字?

【问题讨论】:

  • 但是,如果我想替换的不仅仅是这两个数字,您的意思是将元组传递给f
  • 不,我的意思是我可能想用 7s 替换所有 5s,用 12s 替换所有 8s,等等。

标签: c++ replace std-pair


【解决方案1】:

您可以使用std::map 将要替换的内容存储为键并将替换内容存储为值:

std::pair<int, int> f(std::pair<int, int> p) {
    static const std::map<int, int> replacements = {
        { 2, 3 },  // 2 -> 3
        { 5, 7 }   // 5 -> 7
        // Add more replacements
    };

    auto it = replacements.find(p.first);
    if (it != replacements.end()) {
        p.first = it->second;
    }

    // Same with p.second

    return p;
}

你也可以通过引用来摆脱不必要的副本:

void f(std::pair<int, int>& p) {
    // Same as above, but no return 
}

【讨论】:

    【解决方案2】:

    首先,我将排除 p.firstp.second 之间的重复。

    void maybe_replace_element(int& element)
    {
        if (element == 2)
            element = 3
        else if (element == 3)
            element = 2
    }
    
    pair<int,int> f(pair<int, int> p) {
        maybe_replace_element(p.first);
        maybe_replace_element(p.second);
        return p;
    }
    

    这将 if 语句的数量减半。

    那么,如果你有更多的数字要添加,我认为继续else if 模式是合理的:

    void maybe_replace_element(int& element)
    {
        if (element == 2)
            element = 3
        else if (element == 3)
            element = 2
        else if (element == 5)
            element = 7
        else if (element == 8)
            element = 12
    }
    

    但你也可以使用std::unordered_map

    const std::unordered_map<int, int> REPLACEMENTS = {
        {2, 3}, // Replace 2 with 3.
        {3, 2}, // Replace 3 with 2.
        {5, 7}, // etc.
        {8, 12}
    };
    
    void maybe_replace_element(int& element)
    {
        auto replacement = REPLACEMENTS.find(element);
        if (replacement != REPLACEMENTS.end())
            element = replacement->second;
    }
    

    【讨论】:

    • 甚至是switch/case。与std::map 相比,switch/if 的代码生成非常好(小而快),因此应该更可取。
    猜你喜欢
    • 2011-07-17
    • 2021-11-04
    • 1970-01-01
    • 2023-03-16
    • 2017-07-05
    • 2018-07-23
    • 2022-01-24
    • 1970-01-01
    • 2014-06-16
    相关资源
    最近更新 更多