当我们在向量上使用唯一函数时,移位如何工作?

Bel*_*gor 5 c++ stl vector

所以,我目前正在阅读一些c ++的东西,我在cppreference上看到了这个例子,我无法理解这个转换是如何工作的.

#include <iostream>
#include <algorithm>
#include <vector>

int main() 
{
    std::vector<int> v{1, 2, 2, 2, 3, 3, 2, 2, 1};
    std::vector<int>::iterator last;

    last = std::unique(v.begin(), v.end()); // 1 2 3 2 1 3 2 2 1
                                            //           ^
    for (std::vector<int>::iterator it = v.begin(); it != last; ++it) {
        std::cout << *it << " ";
    }
    std::cout << "\n";
}
Run Code Online (Sandbox Code Playgroud)

我明白,当我们用它独特的东西转移了,但我不知道我们是如何获得给我们的顺序lastv.end().

通过我自己的纸质图纸我知道我们如何从实现的顺序v.begin(),以v.last()从,但不是序列v.last()v.end()提到.

这是参考站点.

Who*_*aig 5

std:unique确实只是根据需要将元素转移到开头.这种转变并不像你想象的那样.它不需要是一次传播一个元素的东西.它可以利用元素必须移动可分配的要求.根据移动赋值的定义,移动元素后,其先前内容未指定.在您的情况下,它只保留"值",但它不是指定的值.

简而言之,您所看到的是剩余价值,其中一些可能是非特定的.

以下是使用您的数据的简单演示.最初我们有两个插槽位置,R和一个W.我没有保证这是使用算法std::unique(我老实说不知道).

根据普通情况(0或1长度序列),当要保持一个值时,它在W上方的下一个时隙中移动分配,并且W被提前.无论是否保留,R始终是先进的.完成后,经过 W 的槽就是last(即左边的第一个槽,其中一些可能有未指定的值).

根据您的数据,序列将是这样的:

1, 2, 2, 2, 3, 3, 2, 2, 1 - different, since the write target
W  R                        is the same as the read-point, do nothing,
                            and advance both R and W

1, 2, 2, 2, 3, 3, 2, 2, 1 - equivalent, advance R only
   W  R                     

1, 2, 2, 2, 3, 3, 2, 2, 1 - equivalent, advance R only
   W     R                     

1, 2, 2, 2, 3, 3, 2, 2, 1 - different, move the 3 to the next write
   W        R               point and advance both R and W

1, 2, 3, 2, 3, 3, 2, 2, 1 - equivalent, advance R only
      W        R

1, 2, 3, 2, 3, 3, 2, 2, 1 - different, move the 2 to the next write
      W           R         slot and advance both R and W

1, 2, 3, 2, 3, 3, 2, 2, 1 - equivalent, advance R only
         W           R      

1, 2, 3, 2, 3, 3, 2, 2, 1 - different, move the 1 to the next write
         W              R   slot and advance both R and W

1, 2, 3, 2, 1, 3, 2, 2, 1 - read is at end-of-sequence
            W             R 
Run Code Online (Sandbox Code Playgroud)

此时,读者已完成.过去W的第一个槽last就像算法一样(end如果原始序列没有重复,则可能确实如此).在完成此操作后,我将向您提出确定哪些元素(3,2,2,1)处于"未指定"状态的挑战.

提示:被移动了什么?跳过了什么?什么被覆盖了?为什么这有关系?试着写0上的任何事物的读出槽移动,看看什么是序列中从吃剩的lastend.