Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the cbegin and cend functions of Clipper 11

Shulou Source: shulou.com Published: 2022-06-01 19:48:34 10月03日 Update

This article introduces the relevant knowledge of "how to use the cbegin and cend functions of Category 11". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Const iterator

Let's take a look at the following program:

Sum = 0

Vector v {1, 2, 3, 4, 5, 6}

Vector::iterator it = v.begin ()

While (it! = v.end ()) {

Sum + = * it

It++

}

The code first gets the iterator for vector, and then iterates through the vector for summation. Take a look at the following code:

Sum = 0

Const vector cv {1, 2, 3, 4, 5, 6}

Vector::iterator cit = cv.begin ()

While (cit! = v.end ()) {

Sum + = * cit

Cit++

}

This code cannot be compiled because the defined vector is of type const, so the iterator must also be of type const. The code needs to be modified as follows:

Sum = 0

Const vector cv {1, 2, 3, 4, 5, 6}

Vector::const_iterator cit = cv.begin ()

While (cit! = v.end ()) {

Sum + = * cit

Cit++

}

Another way is to use the auto type modifier:

Sum = 0

Auto ait = cv.begin ()

While (ait! = cv.end ()) {

Sum + = * ait

Ait++

}

It saves the trouble of manually distinguishing iterator types without interfering with the functionality of const type iterators.

further more

Vector itself is of type const, and the generated iterator must be of type const. In this way, possible changes to vector data are avoided at the compilation level.

There is another case where the data itself is not of type const, but from a design point of view some processes should not modify the data. Iterators of type const should also be required to prevent the data from being accidentally modified.

Cbegin and cend methods are provided for this purpose.

Vector v {1,2,3,4,5,6};

Auto ait = v.cbegin ()

While (ait! = v.cend ()) {

Sum + = * ait

* ait = sum; / / compilation error

Ait++

}

Cbegin () / cend () determines that the type of iterator returned is const. At this point, mismanipulation of the data can be prevented even if the type of vector is not const.

This is the end of the content of "how to use the cbegin and cend functions of Clipper 11". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Tags: Type iteration data code compilation function content situation more knowledge faceted practical unexpected to this end learning and then further manual from design method Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Microsoft Redmi Huawei Apple MariaDB