迭代器超载并导致seg故障

时间:2017-04-21 03:21:36

标签: c++ iterator

所以我有一个迭代器迭代遍历map,其中int作为键,而custom对象作为值。迭代遍历此映射时,迭代器总是会超过存储在映射中的元素数量。我通过强制循环停止当计数器值变得大于地图的大小来解决这个问题,但我很困惑为什么我需要这样做(我很确定解决方案只是击败了迭代器的点) 。这是代码导致问题的部分。 PatronsAddressLibrary都是正在运行的预定义类(因为值正常打印)。

map<int, Patron>::iterator it;
        int counter = 0;
        for(it = library.getPatrons().getPatrons().begin(); it != library.getPatrons().getPatrons().end() && counter < library.getPatrons().getPatrons().size(); ++it){
            cout << library.getPatrons().getPatrons().size() << endl;
            cout << it->second.getName() << endl;
            cout << it->second.getAddress().getStreetAddress() << endl;
            cout << it->second.getAddress().getCity() << ", " <<  it->second.getAddress().getState() << " " << it->second.getAddress().getZip() << endl;
            counter++;
            cout << endl;
        }

如果此循环在没有counter < library.getPatrons().getPatrons().size()检查的情况下迭代单个元素映射,则会输出以下内容:

1 //the size of the map
sdfoji //the name of the owner of the address
sdfio //the street address
sdfio, oifds 77494 //the city, state, and zip code

1
sdfoji
sdfio
sdfio, oifds 77494

1
//seg fault here

正如您所看到的,迭代器迭代了2个不存在的值,似乎忽略了条件it != library.getPatrons().getPatrons().end()

1 个答案:

答案 0 :(得分:1)

你的循环没有清楚地回答错误。很可能你的一个getPatrons()方法按值返回map,你最终将你的迭代器与属于另一个map实例的end()进行比较,因此你的迭代总是超出边界。

这是一个简单的方法来验证我的猜测:

map<int, Patron>::iterator it;
int counter = 0;
map<int, Patron> patrons = library.getPatrons().getPatrons();
for (it = patrons.begin(); it != patrons.end(); ++it) {
    cout << patrons.size() << endl;
    cout << it->second.getName() << endl;
    cout << it->second.getAddress().getStreetAddress() << endl;
    cout << it->second.getAddress().getCity() << ", " << it->second.getAddress().getState() << " " << it->second.getAddress().getZip() << endl;
    counter++;
    cout << endl;
}

如果这样可以解决您的问题,您应该将函数更改为按引用返回(cosnt引用),或者您也可以使用range-based for-loop即使按值返回map也不会出现此问题:

int counter = 0;
for (const auto& it : library.getPatrons().getPatrons()) {
    cout << it.second.getName() << endl;
    cout << it.second.getAddress().getStreetAddress() << endl;
    cout << it.second.getAddress().getCity() << ", " << it.second.getAddress().getState() << " " << it.second.getAddress().getZip() << endl;
    counter++;
    cout << endl;
}
相关问题