For loop iterates through the vector and show all strings on the console successfully:
int main(int argc, const char * argv[])
{
vector<string>stringVector;
string newStringEntry;
cin>>newStringEntry;
stringVector.push_back(newStringEntry);
cin>>newStringEntry;
stringVector.push_back(newStringEntry);
for (vector<string>::iterator i = stringVector.begin(); i != stringVector.end(); ++i)
{
cout<<*i<<endl;
}
}
But this makes the code hard to read (said our teacher) now we have to build a class for the for loop and the main should look like this after the change:
int main(int argc, const char * argv[])
{
vector<string>stringVector;
string newStringEntry;
cin>>newStringEntry;
stringVector.push_back(newStringEntry);
cin>>newStringEntry;
stringVector.push_back(newStringEntry);
showStrings();
}
The problem I see is that I cannot just copy paste the for loop to an own class because
the vector name I declare in the main is not known in the class so I get an error.
How can I get this working?
My class so far looks like this:
class VectorHelp {
void showStrings() const
{
for (vector<string>::iterator i = vectorName.begin();
i != vectorName.end();
++i)
{
cout << *i << endl;
}
}
};
You need to pass your
vector<strings>as a method parameter:Note that the name of your formal and actual parameter do not need to be the same. Also note that
showStringsshould be a class member function (i.e.static), not an instance member function.Finally, note that printing without loops can be done using facilities of the standard C++ library: