問題描述
這些術語在 C++ 中是什么意思?
What do these terminologies mean in C++?
1.
關閉 end
值
2.
半開范圍 - [begin, off_the_end)
我在閱讀 for 循環時遇到了它們.
I came across them while reading about for loops.
推薦答案
半開范圍是包含第一個元素但不包括最后一個元素的范圍.
A half-open range is one which includes the first element, but excludes the last one.
范圍 [1,5) 是半開的,由值 1、2、3 和 4 組成.
The range [1,5) is half-open, and consists of the values 1, 2, 3 and 4.
結束"或結束"指的是序列末尾之后的元素,它的特殊之處在于允許迭代器指向它(但您可能不會查看實際值,因為它不存在)
"off the end" or "past the end" refers to the element just after the end of a sequence, and is special in that iterators are allowed to point to it (but you may not look at the actual value, because it doesn't exist)
例如,在以下代碼中:
char arr[] = {'a', 'b', 'c', 'd'};
char* first = arr
char* last = arr + 4;
first
現在指向數組的第一個元素,而 last
指向數組末尾的一個元素.我們可以指向數組末尾的一個(但不能兩個過去),但我們不能嘗試訪問該位置的元素:
first
now points to the first element of the array, while last
points one past the end of the array. We are allowed to point one past the end of the array (but not two past), but we're not allowed to try to access the element at that position:
// legal, because first points to a member of the array
char firstChar = *first;
// illegal because last points *past* the end of the array
char lastChar = *last;
我們的兩個指針 first
和 last
共同定義了一個范圍,即它們之間的所有元素.
Our two pointers, first
and last
together define a range, of all the elements between them.
如果是半開區間,則包含first
指向的元素,以及中間的所有元素,但不包含last
指向的元素(這很好,因為它實際上并不指向有效元素)
If it is a half open range, then it contains the element pointed to by first
, and all the elements in between, but not the element pointed to by last
(which is good, because it doesn't actually point to a valid element)
在 C++ 中,所有標準庫算法都在這種半開范圍內運行.例如,如果我想將整個數組復制到其他位置 dest
,我會這樣做:
In C++, all the standard library algorithms operate on such half open ranges. For example, if I want to copy the entire array to some other location dest
, I do this:
std::copy(first, last, dest)
一個簡單的 for 循環通常遵循類似的模式:
A simple for-loop typically follows a similar pattern:
for (int i = 0; i < 4; ++i) {
// do something with arr[i]
}
這個循環從 0 到 4,但不包括結束值,所以覆蓋的索引范圍是半開,特別是 [0, 4)
This loop goes from 0 to 4, but it excludes the end value, so the range of indices covered is half-open, specifically [0, 4)
這篇關于什么是半開范圍和離終值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!