为什么这段程序,for 循环最后一个元素打印不出来?

int main()
{
    vector<string> words = {
        "the", "quick", "red", "fox", "jumps", "over", "the", "slow", "the", "turtle", "the"
    };
    sort(words.begin(), words.end());  // 排序
    cout << words.size() << endl;
    for (auto &i : words)
        cout << i << " ";
    cout << endl;

    auto end_unique = unique(words.begin(), words.end()); // 重复元素放在后面
    cout << words.size() << endl;
    for (auto &i : words)
        cout << i << " ";
    cout << endl;

    return 0;
}

运行结果:

11
fox jumps over quick red slow the the the the turtle 
11
fox jumps over quick red slow the turtle the the

size 出来的大小都是正常的,但遍历打印就是少一个。

编译器:g++ 9.4.0

运行环境:Ubuntu 20.04

在使用 unique 函数之后,它将重复元素移到了末尾,因此在末尾的重复元素不会被遍历到。如果想要遍历所有元素,可以使用 end_unique 作为 for 循环的结束条件,而不是 words.end()。修改后代码如下:

for (auto i = words.begin(); i != end_unique; ++i)
    cout << *i << " ";

你的第二个循环用了 unique 函数。

"unique"是C++语言中的STL函数,包含于头文件中。功能是将数组中相邻的重复元素去除。然而其本质是将重复的元素移动到数组的末尾,最后再将迭代器指向第一个重复元素的下标。

unique函数可以去除数组中相邻重复项。

例如:
输入数组 a[]={1,2,3,4,4,5,6,6,6,7,8,6,7,8}。
输出数组 a[]={1,2,3,4,5,6,7,8,6,7,8}。