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 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算