V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
yaron
V2EX  ›  问与答

请教大佬一个 c++值初始化的问题

  •  
  •   yaron · 2022-07-15 15:54:12 +08:00 · 751 次点击
    这是一个创建于 644 天前的主题,其中的信息可能已经有所发展或是发生改变。

    使用无序 map 来记录字符串中字符的个数

    unordered_map<char, int> strmap;
    for (int i = 0; i < s.size(); i++)
    {
      strmap[s[i]]++;
    }
    

    以上的写法是规范的吗?

    strmap[s[i]]++ 看起来好像是先插入,后初始化为 0 ,再进行+1 操作。

    但像int a; 这种,a 的值不是未知的吗

    8 条回复    2022-07-15 17:09:24 +08:00
    Jooooooooo
        1
    Jooooooooo  
       2022-07-15 15:59:25 +08:00
    若是写法让人理解不了, 就换一种更清晰的写法.
    MegrezZhu
        2
    MegrezZhu  
       2022-07-15 16:13:22 +08:00   ❤️ 2
    MegrezZhu
        3
    MegrezZhu  
       2022-07-15 16:14:04 +08:00
    上面这个链接跳转有些问题…记得把后面的[]一起带上
    freemon
        4
    freemon  
       2022-07-15 16:14:22 +08:00   ❤️ 1
    unorderde_map 元素如果是 int 类型,默认值是 0 ,这个依赖于 stl 的实现,int a 这种也不一定是未知的值,依赖不同编译器的实现,有些编译器会将这种设置为 0 ,有些则默认为寄存器中上次预留的值
    404neko
        5
    404neko  
       2022-07-15 16:15:21 +08:00   ❤️ 1
    unordered_map 是模板类
    int 是基础数据类型

    类声明的时候会调用默认构造函数
    yaron
        6
    yaron  
    OP
       2022-07-15 16:23:02 +08:00
    解题:
    A call to this function is equivalent to:
    (*((this->insert(make_pair(k,mapped_type()))).first)).second

    strmap[s[i]]++ 相当于:
    strmap.insert(make_pair(s[i], int()))
    而:
    int() 等于 (int)0
    daC
        7
    daC  
       2022-07-15 16:23:35 +08:00 via Android   ❤️ 1
    T() 的写法是值初始化,对于 int ,也就是零初始化
    结合 2L 的链接,你描述的行为是标准的
    L4Linux
        8
    L4Linux  
       2022-07-15 17:09:24 +08:00 via Android
    int 转 char ,signed 与 unsigned 比较。被打一顿不过分。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2616 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 37ms · UTC 01:47 · PVG 09:47 · LAX 18:47 · JFK 21:47
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.