简体   繁体   English

C ++:仅在一个元素上使用unique_copy

[英]C++: Using unique_copy on just one element

This is the implementation as found on cplusplus.com 这是cplusplus.com上的实现

template <class InputIterator, class OutputIterator>
  OutputIterator unique_copy (InputIterator first, InputIterator last,  
                              OutputIterator result) {
  if (first==last) return result;

  *result = *first;
  while (++first != last) {
    typename iterator_traits<InputIterator>::value_type val = *first;
    if (!(*result == val))   // or: if (!pred(*result,val)) for version (2)
      *(++result)=val;
  }
  return ++result;
}

So when when "first" and "last" iterators point to the same element, we don't return anything? 那么当“first”和“last”迭代器指向同一个元素时,我们不会返回任何内容? That seems out-of-line with unique_copy's definition: the first element from every consecutive group of equivalent elements in the range [first,last) is copied. 这似乎与unique_copy的定义不符:复制范围[first,last]中每个连续等效元素组的第一个元素。 Is it because of the "last)" part? 是因为“最后”部分吗? Can anyone clarify? 任何人都可以澄清吗? Thanks! 谢谢!

You are correct that the [first, last) is the problem. 你是对的,[第一个,最后一个]是问题。

When assigning iterators to containers, it is standard that the last iterator you can possible have is to the memory position 1 iteration after the last element in the container. 将迭代器分配给容器时,标准的是,您可以使用的最后一个迭代器是在容器中的最后一个元素之后的内存位置1迭代。

Ex. 防爆。

vector<int> aVec{5,-8,23,200};
vector<int>::iterator currentItr, lastItr;

// iterator to first element, 5
currentItr = aVec.begin(); 


// iterator to element ***directly after*** last element
lastItr = aVec.end();
// in other words, there is no reason to access the value attached to lastItr

One reason why the .end() standard exists is to easily tell when the currentItr has reached past the usable values in a container; 存在.end()标准的一个原因是容易告诉currentItr何时达到容器中的可用值;

Ex. 防爆。

while (currentItr != lastItr) // currentItr will not print once it's equal to lastItr
    cout << *currentItr++ << endl;

In your specific example, if there is one element in a container, then the iterators [first, last) should not be equal. 在您的具体示例中,如果容器中有一个元素,则迭代器[first,last]不应该相等。 "first" is an iterator located one element to the left of iterator "last". “first”是一个迭代器,位于迭代器“last”左侧的一个元素。

If first == last, then the span of possible iterators is: 如果first == last,那么可能的迭代器范围是:

[first, first) or [last, last) [第一个,第一个]或[最后一个,最后一个]

The possible span cannot both include and exclude any iterator. 可能的跨度不能同时 包含 排除任何迭代器。 That sounds crazy. 这听起来很疯狂。

Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM