乐闻世界logo
搜索文章和话题

What is the difference between cbegin and begin for vector?

1个答案

1

In C++, std::vector provides various methods to access its elements, including begin and cbegin. The main difference between these two methods lies in the type of iterator they return.

  1. begin() Method:

    • begin() returns an iterator pointing to the first element of the container.
    • This iterator is mutable, allowing modification of elements in the container through it.
    • For non-const objects, begin() returns an iterator type; for const objects, it returns a const_iterator.
  2. cbegin() Method:

    • cbegin() also returns an iterator pointing to the first element of the container.
    • However, this iterator is constant, meaning you cannot modify elements in the container through it.
    • Regardless of whether the container is const, cbegin() always returns a const_iterator type iterator.

Example

Consider the following C++ code example demonstrating the use of begin() and cbegin():

cpp
#include <iostream> #include <vector> int main() { std::vector<int> v = {1, 2, 3, 4, 5}; // Using begin() to get an iterator and modify elements auto it = v.begin(); *it = 10; // Change the first element to 10 // Using cbegin() to get a constant iterator auto cit = v.cbegin(); // *cit = 20; // Uncommenting this line would cause a compilation error, as cit is a const_iterator // Output the modified vector contents for (auto i : v) { std::cout << i << " "; } return 0; }

In this example, the iterator returned by begin() modifies the first element of the vector. Attempting to modify elements through the constant iterator returned by cbegin() would result in a compilation error because it is read-only.

In summary, the choice between begin() and cbegin() depends on whether you need to modify elements accessed through the iterator. If you want to ensure data is not modified, using cbegin() is a good choice.

2024年7月4日 11:24 回复

你的答案