这些术语在 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模板网!
当没有异常时,C++ 异常会以何种方式减慢代码速In what ways do C++ exceptions slow down code when there are no exceptions thown?(当没有异常时,C++ 异常会以何种方式减慢代码速度?)
为什么要捕获异常作为对 const 的引用?Why catch an exception as reference-to-const?(为什么要捕获异常作为对 const 的引用?)
我应该何时以及如何使用异常处理?When and how should I use exception handling?(我应该何时以及如何使用异常处理?)
C++中异常对象的范围Scope of exception object in C++(C++中异常对象的范围)
从构造函数的初始化列表中捕获异常Catching exceptions from a constructor#39;s initializer list(从构造函数的初始化列表中捕获异常)
C++03 throw() 说明符 C++11 noexcept 之间的区别Difference between C++03 throw() specifier C++11 noexcept(C++03 throw() 说明符 C++11 noexcept 之间的区别)