void Document::loadFile(string iFileExt)
{
ioFile = new fstream(iFileExt.c_str(), ios::in); // does this ever get deleted?
// string *content; // arrays have their place, and this is not it
std::vector<string> content;
if (ioFile->fail()){
cerr << "File failed to open for read" << endl;
exit(69); // don't ever just unconditionally exit from random places
// it makes for unmaintainable spaghetti code
}
for (int i = 0; ioFile->good(); ++i) // loop manages i for us
{
content.push_back((string()));
getline (*ioFile, content[i]);
}
ioFile->close();
}
在将使用指针数组的现有代码替换为采用向量的代码时,以下内容可能很有用。
该函数可能具有如下签名:
void ProcessLinesInFile(int numLines, std::string *lines[]); // maybe this
void ProcessLinesInFile(int numLines, std::string **lines); // or maybe this
两种方式本质上是等价的。
ProcessLinesInFile
可能有这样的身体:
for (int i = 0; i < numLines; ++i)
{
*lines[i] = Process(*lines[i]); // read and maybe write the line
}
第一步是让它使用字符串数组,而不是字符串指针数组:
void ProcessLinesInFile(int numLines, std::string lines[])
{
// should behave exactly the same way as before
for (int i = 0; i < numLines; ++i)
{
lines[i] = Process(lines[i]); // read and maybe write the line
}
}
从那里开始,使用向量很容易:
void ProcessLinesInFile(std::vector<std::string> &lines)
{
// should behave exactly the same way as before
for (int i = 0; i < lines.size(); ++i)
{
lines[i] = Process(lines[i]); // read and maybe write the line
}
}
如果您确定在整个过程中不需要实际更改数组,您可以(并且谨慎地)将向量引用作为常量传递:
void ProcessLinesInFile(std::vector<std::string> const &lines);