doulu7921 2013-02-08 20:46
浏览 54
已采纳

为什么我在使用未定义索引时没有收到错误?

I'm from php and when I define something like this:

$a = array();
echo $a[586];

I will get a notice about undefined index.

Meanwhile at c++ I can do this:

map<int, string> my_map;
cout << "Map is: " << my_map[34535];

string sentence = "acdefb s";
cout << "Letter is: " << sentence[15];

And I won't get any error.

Why it's not possible at php and possible at c++?

  • 写回答

3条回答 默认 最新

  • drnmslpz42661 2013-02-08 20:47
    关注

    Because PHP and C++ are two radically different languages with radically different semantics. When using the [] operator with an std::map object in C++, a new element is inserted into the map if the key does not already exist within the map. In PHP, this is not the case.

    As for your second example with std::string sentance, it is not valid to use the [] operator with an invalid index (an index which is >= sentance.length()) on an std::string in C++. You may not get any "error", because the result of using an invalid index with std::string is undefined behavior, meaning that anything can happen. One common result on modern platforms is a Segmentation Fault/Access Violation, which generally will crash your program.

    With std::string you can use std::string::at() instead of the [] operator if you want protection against undefined behavior. The at function does a bounds check and throws std::out_of_range if you use an invalid index.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊