当我在此代码中调用 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
的字符串 vector (实际上是整数列表),它被解析为整数并存储在多维 vector 中。 unique() 旨在从创建的整数 vector 中去除重复项。
无论如何,我的问题是:如何让 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.
强调原文。返回只是结束应该的地方——这个算法实际上并没有从容器中删除任何元素,因为在一般情况下它不知道如何做到这一点。
这就是为什么您需要获取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
仅删除连续 个重复项 - 而不是所有 个重复项。如果您真的想要真正独特的结果,您需要先对 vector 进行排序
。
关于c++ - unique() 似乎正在添加最后一个元素的另一个拷贝,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28335997/