Dee*_*psy 3 c++ crash intersection std
我试图找到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));
Run Code Online (Sandbox Code Playgroud)
它编译成功,但是在运行该程序后,即时崩溃并显示以下错误:

有什么建议导致此问题吗?
您应该先进行排序a,b然后再将它们传递给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<,第二个版本期望用给定的比较函数对它们进行排序comp。
因此,添加
std::sort(a.begin(), a.end());
std::sort(b.begin(), b.end());
Run Code Online (Sandbox Code Playgroud)