unique() 似乎正在添加最后一个元素的另一个副本

unique() seems to be adding another copy of the last element

当我在此代码中调用 unique() 时,输出最终会在末尾附加最后一个元素的副本。

vector<vector<int>> ints;
for(int i(0); i<files; i++)
{
    stringstream stream(list[i]);
    int num(0);
    vector<int> aList;
    for(int j(0); j<list[i].length(); j++)
    {
        if(stream.peek() == ' ')
                stream.ignore();
        while (stream >> num)
        {
            aList.push_back(num);
            if(stream.peek() == ' ')
                stream.ignore();
        }
    }
    ints.push_back(aList);
    unique(ints[i].begin(), ints[i].end());
}

我有一个名为 list 的字符串向量(实际上是整数列表),它被解析为整数并存储在多维向量中。 unique() 旨在从创建的整数向量中去除重复项。

无论如何,我的问题是:如何让 unique() 停止添加额外的元素?

如果您查看 std::unique 的文档,您会注意到它:

Removes all consecutive duplicate elements from the range [first, last) and returns a past-the-end iterator for the new logical end of the range.

强调原文。 return 只是结束 应该 的地方 - 该算法实际上不会从容器中删除任何元素,因为它不知道在一般情况下如何执行此操作.

这就是为什么您需要获取 unique 的结果并将其传递给 erase。来自文档中的示例:

auto last = std::unique(v.begin(), v.end());
v.erase(last, v.end());

或针对您的具体情况:

ints[i].erase(
    // new logical end 
    std::unique(ints[i].begin(), ints[i].end()),
    // actual end
    ints[i].end());

另请注意,unique 仅删除 个连续 个重复项 - 而不是 所有 个重复项。如果你真的想要真正独特的结果,你需要先 sort 你的矢量。

您误解了 std::unique 的作用。它不会从容器中删除任何元素。它只是移动元素,以便将唯一元素推到前面。

它returns 一个标记容器逻辑结束的迭代器。容器的物理端保持不变。

容器的逻辑端和容器的物理端之间的元素具有未指定的值。

来自http://en.cppreference.com/w/cpp/algorithm/unique

Removing is done by shifting the elements in the range in such a way that elements to be erased are overwritten. Relative order of the elements that remain is preserved and the physical size of the container is unchanged. Iterators pointing to an element between the new logical end and the physical end of the range are still dereferenceable, but the elements themselves have unspecified values. A call to unique is typically followed by a call to a container's erase method, which erases the unspecified values and reduces the physical size of the container to match its new logical size.