I have a vector of pointers to objects that I am iterating through using std::vector::iterator`. Since the element returned is itself a pointer I dereference the iterator twice, once to return the pointer and once to resolve the pointer to the actual object.
I'm trying to invoke a member function (getClass
) that returns an std::string and I have tried both (**it).getClass()
and (*it)->getClass()
but both give me a segmentation fault. I keep feeling like I'm missing something obvious.
partial function code:
void dataSet::createFolds()
{
// Shuffle the data vector
std::random_shuffle( m_records.begin(), m_records.end());
std::cout << "STARTING MAIN LOOP. THERE ARE " << m_records.size() << " RECORDS\n";
// iterate through the data vector and assign each to a fold
std::vector<dataRecord *>::iterator it = m_records.begin();
while (it != m_records.end())
{
std::string currentClass = (*it)->getClass(); // SEG FAULT HERE
.
.
.
}
.
.
.
}
The vector is m_records ... code
dataRecord is defined like this ... code
In response to questions about filling the vector:
The data is read from a text file and I really don't want to post the entire thing unless I have to (212 lines) but the pertinent code for populating the vector is below. The constructor for the dataRecord object takes a vector of field objects. I use a temporary pointer, use new to create the object then push_back the pointer.
while ...
{
std::vector<field> fields;
// build the fields vector
for (unsigned int i = 0; i < numAttribs; ++i)
fields.push_back(field(data.at(i), attribTypes[i]));
// create the new dataRecord
dataRecord * newRecord = new dataRecord(fields);
// add the record to the set
m_records.push_back(newRecord);
++recordNum;
std::cout << "read record " << recordNum << std::endl;
}
In my opinion the vector elements are badly initialized. Perhaps you have to test the code that fill the vector independently before testing to extract them. Sorry for my english ;)