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++?
Because PHP and C++ are two radically different languages with radically different semantics. When using the
[]operator with anstd::mapobject 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 anstd::stringin C++. You may not get any “error”, because the result of using an invalid index withstd::stringis 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::stringyou can usestd::string::at()instead of the[]operator if you want protection against undefined behavior. Theatfunction does a bounds check and throwsstd::out_of_rangeif you use an invalid index.