I think I’ve declared a Vector with an object correctly. But, I don’t know how to access it’s members when looping with Iterator.
In my code, the line —>> cout << ‘ ‘ << *Iter;
How do I print the contents of the members? Like *Iter.m_PackLine ???
Not sure if I used the correct terminology, but appreciate the help! Thanks
class CFileInfo { public: std::string m_PackLine; std::string m_FileDateTime; int m_NumDownloads; }; void main() { CFileInfo packInfo; vector<CFileInfo, CFileInfo&> unsortedFiles; vector<CFileInfo, CFileInfo&>::iterator Iter; packInfo.m_PackLine = 'Sample Line 1'; packInfo.m_FileDateTime = '06/22/2008 04:34'; packInfo.m_NumDownloads = 0; unsortedFiles.push_back(packInfo); packInfo.m_PackLine = 'Sample Line 2'; packInfo.m_FileDateTime = '12/05/2007 14:54'; packInfo.m_NumDownloads = 1; unsortedFiles.push_back(packInfo); for (Iter = unsortedFiles.begin(); Iter != unsortedFiles.end(); Iter++ ) { cout << ' ' << *Iter; // !!! THIS IS WHERE I GET STUMPED // How do I output values of the object members? } } // end main
will only work if
CFileInfohas an overloadedoperator<<that can output your struct. You can output individual members of the struct instead like this:Alternatively, the following is equivalent to that:
You have to put parentheses around *Iter, since the member-access operator binds thighter otherwise.
On a side-node, make your main function return int instead of void. making it return void is not valid in C++.
You declare the vector like this:
The second argument to
vectorshould be another thing. It’s not needed for your code to give the vector a second argument at all. Just use this:Another thing i noticed is you increment the iterator using
Iter++(calledpostfix increment). For iterators, always prefer++Iter, which is calledprefix increment.