什么是半开放范围和终值 [英] What is half open range and off the end value

查看:119
本文介绍了什么是半开放范围和终值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这些术语在C ++中意味着什么?



1。 value



2。半开区间 - [begin ,off_the_end)



我在阅读有关for循环时遇到了他们。

解决方案

半开范围是包括第一个元素的范围,但不包括最后一个元素。



范围[1,5 )是半开的,并且由值1,2,3和4组成。



结束或结束指的是元素之后,因为迭代器允许指向它(但是你可能不看实际值,因为它不存在)。



例如,在以下代码中:

  char arr [] = {'a' ,'b','c','d'}; 

char * first = arr
char * last = arr + 4;

第一个现在指向第一个元素数组,而 last 指向一个超过数组末尾。我们允许指向一个超过数组末尾(但不是两个过去),但我们不允许尝试访问该位置处的元素: / p>

  //合法,因为首先指向数组的成员
char firstChar = * first;
//非法的,因为最后点*过去*数组的结尾
char lastChar = * last;

我们的两个指针,第一 c $ c> last 一起定义它们之间所有元素的范围。



如果它是一个半开放范围, 第一指向的元素,以及之间的所有元素,但不是 last 指向的元素是好的,因为它实际上不指向有效的元素)



在C ++中,所有标准库算法都在这样的半开放范围上操作。例如,如果我要将整个数组复制到其他位置 dest ,我这样做:

  std :: copy(first,last,dest)

for-loop通常遵循类似的模式:

  for(int i = 0; i <4; ++ i) 
//使用arr执行操作[i]
}

从0到4,但是它排除了结束值,因此覆盖的索引的范围是<半开的,具体地 [0,4) / p>

What do these terminologies mean in C++?

1. off the end value

2. half open range - [begin, off_the_end)

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.

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)

For example, in the following code:

char arr[] = {'a', 'b', 'c', 'd'};

char* first = arr
char* last = arr + 4;

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;

Our two pointers, first and last together define a range, of all the elements between them.

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)

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)

A simple for-loop typically follows a similar pattern:

for (int i = 0; i < 4; ++i) {
    // do something with arr[i]
}

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)

这篇关于什么是半开放范围和终值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆