Vectors problem

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
Dominik Michniewski
Guru
Posts: 834
Joined: Wed May 29, 2002 4:11 pm
Location: Wroclaw, Poland
Contact:

Vectors problem

Post by Dominik Michniewski »

Could anyone tell me which difference is between this to lines of code ?

We assume that v is type: vector<int> v;

Code: Select all

v[i]
and

Code: Select all

*(v.begin()+i)
In my program first line cuases RTE. Why ? In my opinion this two lines have the same meaning ....

Regards
Dominik Michniewski
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba »

It works fine on my PC. Could you show the code that doesn't want to work?
Dominik Michniewski
Guru
Posts: 834
Joined: Wed May 29, 2002 4:11 pm
Location: Wroclaw, Poland
Contact:

Post by Dominik Michniewski »

Problem is, that n computer (Windows 2K, VC++) always is OK. I try now to install Linux, and I try it again. But problem appears in online jugde. ...

Best regards
DM
If you really want to get Accepted, try to think about possible, and after that - about impossible ... and you'll get, what you want ....
Born from ashes - restarting counter of problems (800+ solved problems)
Krzysztof Duleba
Guru
Posts: 584
Joined: Thu Jun 19, 2003 3:48 am
Location: Sanok, Poland
Contact:

Post by Krzysztof Duleba »

[cpp]#include <iostream>
#include <vector>

using namespace std;

int main()
{
vector<int> v(50,50);
cout<<v[5]<<endl<<*(v.begin()+5)<<endl;
}[/cpp]

This code works fine under Win2k+Cygwin/g++ 2.95/3.2 and Linux with g++ 2.95.

As for the difference you asked, there is no. Look at the definition of operator[] in stl's header file:

[cpp]reference operator[](size_type __n) { return *(begin() + __n); }[/cpp]

It's just the same.
Dominik Michniewski
Guru
Posts: 834
Joined: Wed May 29, 2002 4:11 pm
Location: Wroclaw, Poland
Contact:

Post by Dominik Michniewski »

Hmm, you have right. I must have other problem with my code , but when I send my code with such changes (operator[] was changed to 'begin()+i') I've got WA instead of RTE, so I think that was a problem :)

Best regards fo help
DM
If you really want to get Accepted, try to think about possible, and after that - about impossible ... and you'll get, what you want ....
Born from ashes - restarting counter of problems (800+ solved problems)
Post Reply

Return to “C++”