3

我在我的程序中创建了一个集合向量,我需要遍历每个集合。如果在集合中找到特定元素,我需要向向量添加一个新集合。但是,一旦我的数组的计数器到达我稍后插入的元素(在循环内),这就会给我一个分段错误。在下面的代码中,打开 list.push_back(cS) 会给我一个分段错误。

int main(void)  {
set<int> cS;
vector<set<int> > list;

cS.insert(1);
list.push_back(cS);

cS.insert(2);
list.push_back(cS);

for (int ctr = 0; ctr < list.size(); ctr++)
{
    for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
    {
        if (*itr == 1 || *itr == 2)
        {
            cS.clear();
            cS.insert(3);
            //list.push_back(cS);
        }
    }
}

for (int ctr = 0; ctr < list.size(); ctr++)
{
    for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
    {
        cout << *itr << endl;
    }
}

return 0;
}

如果有人能解释为什么这会出错(在 gcc 中),我将不胜感激。

感谢您浏览我的帖子。

4

1 回答 1

6

当您push_back进入向量时,如果向量需要分配更多内存,则对其中的元素的所有引用都无效。在您的情况下,迭代器itrpush_back. 一种解决方案是将集合添加到单独的列表(向量)中,然后在 for 循环之后一次将它们全部附加:

vector<set<int> > add;
for (int ctr = 0; ctr < list.size(); ctr++)
{
    for (set<int>::iterator itr = list[ctr].begin(); itr != list[ctr].end(); itr++)
    {
        if (*itr == 1 || *itr == 2)
        {
            cS.clear();
            cS.insert(3);
            add.push_back(cS);
        }
    }
}
list.insert(list.end(), add.begin(), add.end());
于 2012-03-23T07:39:33.560 回答