代码之家  ›  专栏  ›  技术社区  ›  Brian

映射递减迭代器给出奇怪的结果?

  •  2
  • Brian  · 技术社区  · 3 年前

    似乎无法解决这个问题。下面是一个简单的例子:

    #include <iostream>
    #include <map>
    
    int main() {
    
        std::map<uint32_t, char> m;
        
        m[1] = 'b';
        m[3] = 'd';
        m[5] = 'f';
        
        std::map<uint32_t, char>::iterator i = m.lower_bound('d');
        
        std::cout << "First: " << i->first << std::endl;
        
        // Decrement the iterator
        i--;
        
        // Expect to get 1, but get 5?
        std::cout << "Second: " << i->first << std::endl;
    
        return 0;
    }
    

    输出为:

    First: 3
    Second: 5
    

    为什么我在这里得到5分?我认为递减迭代器会导致它指向键1

    2 回复  |  直到 3 年前
        1
  •  4
  •   Vlad from Moscow    3 年前

    这个电话

    std::map<uint32_t, char>::iterator i = m.lower_bound('d');
    

    返回迭代器 m.end() .所以取消对迭代器的引用

    std::cout << "First: " << i->first << std::endl;
    

    导致未定义的行为。

    成员函数 lower_bound 需要指定键而不是值的参数。

    考虑下面的演示程序。

    #include <iostream>
    #include <iomanip>
    #include <map>
    #include <cstdint>
    
    int main()
    {
        std::map<uint32_t, char> m;
    
        m[1] = 'b';
        m[3] = 'd';
        m[5] = 'f';
    
        std::map<uint32_t, char>::iterator i = m.lower_bound( 'd' );
    
        std::cout << "i == m.end() is " << std::boolalpha << ( i == m.end() ) << '\n';
    }
    

    程序输出为

    i == m.end() is true
    

    相反,你可以写一些例子

    std::map<uint32_t, char>::iterator i = m.lower_bound( 5 );
    

    在此调用后递减迭代器之后

    标准::地图<uint32_t,char>::迭代器i=m.下界('d');
    

    它指向地图的最后一个元素。

        2
  •  1
  •   Jeffrey    3 年前

    lower_bound 将键而不是值作为输入。这将如您所料:

    std::map<uint32_t, char>::iterator i = m.lower_bound(3);
    

    下界 你在使用,你最终会发现 end() 然后重复一次。