Reputation: 180
Why can't i do like this? In the below code, I can access from for loop, but not from outside loop?
class root
{
string name;
public:
root()
{
}
root(const string& okay)
{
name = okay;
}
void setRoot(const string& okay)
{
name = okay;
}
string getRoot()
{
return name;
}
~root ()
{
}
}; // class root
int main()
{
string a;
vector<root> Root;
vector<root>::iterator oley;
root okay;
for (int i=0; i<5;i++) //this is to add strings in vector
{
cin >> a;
okay.setRoot(a);
Root.push_back(okay);
}
for (oley=Root.begin(); oley!=Root.end(); oley++) //this is to print vectors in scren
{
cout << (*oley).getRoot() << endl;
}
oley = Root.begin();
cout << (*oley + 2).getRoot(); //this is error. What is required to make it legal?
return 0;
}
So, if we can access iterator from for loop, why can't we do so in non-looped codes?
cout << (*oley + 2).getRoot();
Upvotes: 1
Views: 55
Reputation: 45410
This is because of C++ operator precedence, *oley+2
is interpreted as (*oley) + 2
which is becomes root + 2
update
cout<<(*oley+2).getRoot();
to
cout<<(*(oley+2)).getRoot();
or
cout<<oley[2].getRoot();
Upvotes: 4