管理迭代器容器(list迭代器的vector)的段错误修复需求
Hey there! Let's fix your code step by step and get your intended workflow working smoothly. The immediate crash is a simple vector out-of-bounds issue, and your core idea of using a vector to store list iterators is actually totally valid—we just need to tweak a few small things.
First: Why the Segmentation Fault?
When you initialize tVecTest myvec;, the vector starts with a size of 0. Trying to assign to myvec[i] in your loop is accessing memory that doesn't exist yet, which triggers the segfault. We need to properly add elements to the vector instead of directly accessing uninitialized indices.
Second: Your Iterator Storage Idea is Solid
List iterators don't invalidate when other elements are inserted or deleted (only the iterator pointing to a deleted element becomes invalid). So storing tListTest::iterator directly in the vector works perfectly for your use case—no need for reference_wrapper here, that was adding unnecessary complexity.
Modified Working Code
Here's the fixed version with key changes marked:
#include <iostream> #include <list> #include <vector> using namespace std; typedef struct _data { int d; } tData; typedef list <tData *> tListTest; typedef vector <tListTest::iterator> tVecTest; int main() { tListTest mylist; tVecTest myvec; // Optional: Reserve space upfront to avoid repeated vector resizing myvec.reserve(10); tData *myData; int i; for (i=0; i<10; i++) { cout << "Iteration " << i << endl; cout << "Stage 1" << endl; myData = new tData; cout << "Stage 2" << endl; myData->d = i; cout << "Stage 3" << endl; tListTest::iterator listIter = mylist.insert(mylist.end(), myData); cout << "Stage 4" << endl; // Replace direct index assignment with push_back to safely add elements myvec.push_back(listIter); cout << "Stage 5" << endl; } tListTest::iterator listIter = myvec[7]; cout << "Deleting " << (*listIter)->d << endl; delete *listIter; mylist.erase(listIter); // Clean up remaining allocated data to avoid memory leaks for (auto iter : mylist) { delete iter; } return 0; }
Alternative: Using Index Assignment
If you prefer to use myvec[i] instead of push_back, just add myvec.resize(10); right after initializing the vector. This pre-allocates 10 default-constructed iterators, making index access valid.
Why This Works for Your Use Case
- You can still use the list to manage priority: moving elements to
front()orback()is fast, and deleting elements via their stored iterator is an O(1) operation. - The vector lets you access any list element in O(1) time by grabbing its iterator directly, which is exactly what you wanted.
内容的提问来源于stack exchange,提问作者user9250533

