【问题标题】:Expression: Sequence not ordered表达式:序列未排序
【发布时间】:2014-04-27 03:17:59
【问题描述】:

我正在尝试找到 2 个字符串之间的交集。我正在使用以下代码:

std::string a = "asd", b = "afd";

std::string intersect;
std::set_intersection(a.begin(), a.end(), b.begin(), b.end(), std::back_inserter(intersect));

它编译成功,但运行程序后立即崩溃并出现以下错误:

任何建议是什么导致了这个问题?

【问题讨论】:

  • 错误信息告诉你——set_intersection 的输入需要排序。

标签: c++ crash std intersection


【解决方案1】:

您应该先对ab 进行排序,然后再将它们传递给std::set_intersection()

template< class InputIt1, class InputIt2, class OutputIt > OutputIt set_intersection( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first ); (1) template< class InputIt1, class InputIt2, class OutputIt, class Compare > OutputIt set_intersection( InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp ); (2)

构造一个从d_first 开始的排序范围,由在两个排序范围[first1, last1)[first2, last2) 中找到的元素组成。 第一个版本希望两个输入范围都使用operator&lt; 进行排序,第二个版本希望它们使用给定的比较函数comp 进行排序

所以,添加

std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多