Home > Backend Development > C++ > Const Map Access: Why Use `at()` Instead of `operator[]`?

Const Map Access: Why Use `at()` Instead of `operator[]`?

DDD
Release: 2024-12-04 09:30:12
Original
337 people have browsed it

Const Map Access: Why Use `at()` Instead of `operator[]`?

Accessing Elements in a Const Map: Operator[] vs. at()

When working with constant maps, accessing elements using operator[] may fail. However, using at() is a viable alternative. Why is this the case?

In a non-const map, operator[] performs two functions:

  • If the key exists, it returns a reference to the associated value.
  • If the key doesn't exist, it constructs a default-constructed value associated with the key and returns a reference to it.

However, in a const map, operator[] is not allowed to modify the underlying data structure. Hence, it can only perform the first function and throws an error when trying to insert a new element using the second function.

In contrast, at() is a method introduced in C 11 specifically for accessing elements in a const map. It provides several benefits:

  • It throws a std::out_of_range exception if the key doesn't exist, making it consistent with other containers like vector and deque.
  • It has a const overload, allowing its use on const maps.

For these reasons, at() is the recommended method for accessing elements in a const std::map. The example code:

#include <iostream>
#include <map>

int main()
{
    std::map<int, char> A;
    A[1] = 'b';
    A[3] = 'c';

    const std::map<int, char>& B = A;

    std::cout << B.at(3) << std::endl; // it works
    std::cout << B[3] << std::endl;    // it does not work
}
Copy after login

Will output:

c
error: can't access elements with operator[] in a const std::map
Copy after login

The above is the detailed content of Const Map Access: Why Use `at()` Instead of `operator[]`?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template