简体   繁体   English

C ++容器上的段故障循环

[英]Seg Fault Looping over C++ containers

Here's the code(find union of 2 sets) : 这是代码(查找2套并集):

template <class dtype>
void printSet(dtype data)
{
    std::cout<<"\n";
    for(auto i = data.begin(); i != data.end(); i++)
    {
        std::cout<<*i<<" ,";
    }
}

int main(int argc, char const *argv[])
{
    int arr[] = {1,2,3,4,5};
    std::set<long long> a(arr, arr + 5), b(arr, arr + 5), c;
    std::vector<long long> v;
    b.insert(1000);
    printSet(a);
    printSet(b);
    set_union(a.begin(), a.end(), b.begin(), b.end(), v.begin());
    printSet(v);
    return 0;
}

And here's what I got: 这就是我得到的:

1 ,2 ,3 ,4 ,5 ,
[1]    9444 segmentation fault  ./a.out

Where did I mess up ? 我在哪里弄糟?

v is empty, so writing to v.begin() isn't possible. v为空,因此无法写入v.begin() You should use std::back_inserter(v) instead. 您应该改用std::back_inserter(v)

set_union expects a valid output iterator, in the sense that it should be allowed to write at that iterator. 在应该允许set_union写入该迭代器的意义上, set_union期望有效的输出迭代器。 v is empty, so v.begin() isn't a valid iterator. v是空的,因此v.begin()不是有效的迭代器。

Try declaring your vector as 尝试将向量声明为

std::vector<long long> v(42);

For clarity: if you flush std::cout before the set_union line, you should see that b was printed as well. 为了清楚起见:如果在set_union行之前刷新std::cout ,则应该看到b也已打印。

As to the error, I suggest adding this include: 对于错误,我建议添加以下内容:

#include <iterator>

and changing your set_union line to: 并将您的set_union行更改为:

set_union(a.begin(), a.end(), b.begin(), b.end(), back_inserter(v));

The back_insert_iterator returned by back_inserter is an output iterator suitable for use here: it will call v.push_back for each item assigned to it by set_union . back_insert_iterator返回的back_inserter是适合在此使用的输出迭代器:它将为v.push_back为其分配的每个项目调用set_union


A note on your platform & environment: 有关您的平台和环境的说明:

In general, you should make sure your core file size limit is non-zero (just make it unlimited unless you're writing massive programs), and learn to examine the core file with your debugger. 通常,您应确保核心文件大小限制为非零(除非编写大型程序,否则请使其不受限制),并学会使用调试器检查核心文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM