【问题标题】:Correct usage of C++ STL set_symmetric_difference?正确使用 C++ STL set_symmetric_difference?
【发布时间】:2020-12-04 20:28:54
【问题描述】:

在 C++ 中,我想使用 algorithm 中的 set_symmetric_difference 获取两个 STL 集合并生成一个集合,其中包含不在两个集合中的所有元素。

我收到一个编译错误“'_UDest': you cannot assign to a variable that is const”,所以我误解了如何使用set_symmetric_difference

代码如下(C++编译器为Visual Studio 2019):

set<unsigned short> a, b, diff;
// code to add entries to a and b
set_symmetric_difference(a.begin(), a.end(), b.begin(), b.end(), diff.begin()); // error C3892: '_UDest': you cannot assign to a variable that is const

【问题讨论】:

  • 您不能使用diff.begin() 插入。查看std::inserter
  • 您不能像写入向量或双端队列那样写入已排序的容器。他们是完全不同的野兽。您似乎缺乏基础知识:获得一本好的教学书籍。你不能通过反复试验来学习 C++!
  • @curiousguy:如果diffvectordeque,那将无法正常工作。您需要充分调整其大小或使用std::back_inserter 作为序列容器。
  • @FredLarson 这对常规向量迭代器不起作用,而且您不会收到编译时错误,只有内存损坏!

标签: c++ stl set


【解决方案1】:

您将一个迭代器传递给空集diff,作为您的“输出迭代器”。迭代器不是这样工作的。 diff.begin() 指的是现有的 元素(其中没有)。

Set 元素是不可变的(为了保持它们的顺序不变性,它们必须是不可变的),这就是您收到的 特定 错误消息与 constness 相关的原因。但是,如果没有这个因素,您仍然会尝试写入不存在的元素。

您可以改用特殊的 std::inserter 魔术迭代器将插入包装到 diff 中,就像在 the set_symmetric_difference usage example on cppreference 中一样(尽管那个使用排序的 std::vector "sets" 而不是 @987654330 @,所以它可以使用std::back_inserter)。

这是一个例子:

std::set<unsigned short> a, b, diff;
// (code to add entries to a and b)

std::set_symmetric_difference(
   a.begin(), a.end(),
   b.begin(), b.end(),
   std::inserter(diff, diff.begin())  // <---
);

为此,您需要#include &lt;iterator&gt;

【讨论】:

    猜你喜欢
    • 2018-02-26
    • 2017-08-11
    • 1970-01-01
    • 1970-01-01
    • 2022-01-03
    • 2023-03-15
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多