By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
446,260 Members | 1,338 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 446,260 IT Pros & Developers. It's quick & easy.

strange behavior of vector template iterator

nicolaennio
P: 3
I am new with c++ and I cannot understand why this code:

Expand|Select|Wrap|Line Numbers
  1. #include <cstdlib>
  2. #include <iostream>
  3. #include <vector>
  4.  
  5. using namespace std;
  6.  
  7. vector<int>::iterator _begin(vector<int> v){
  8.     return v.begin();
  9. }
  10.  
  11. int main(int argc, char *argv[])
  12. {
  13.     vector<int> v;
  14.     v.push_back(4);
  15.     vector<int>::iterator b = _begin(v);
  16.     printf("%d\n",*b);
  17.     printf("%d\n",*_begin(v));
  18.  
  19.     system("PAUSE");
  20.     return EXIT_SUCCESS;
  21. }
  22.  
gives me this output:
0
4

thanks
Feb 24 '07 #1
Share this Question
Share on Google+
4 Replies


100+
P: 1,646
Well I get -17890612 for both. And this is not beginner stuff :)
Feb 24 '07 #2

nicolaennio
P: 3
thanx for trying it out, actually I am not a beginner in programming, but in c++ yes and I have some difficulties.
I tried it at home and I get something like
40546540
4
Since code is small I could code around this problem, but I need using vector rather than stack and hope it is a problem like "say to the compiler what template you use and ... (it will say who you are :-) )".
It is strange that in your case neither printf worked
Feb 24 '07 #3

nicolaennio
P: 3
ok, I find out the problem, since vector I pass in input is by value a copy is made
in the function and iterator work on the copy, so I return a useless iterator.
I don't know why on my machine it printed 0 rather than an impossible value as willakawill.
Feb 25 '07 #4

100+
P: 1,646
Excellent work. Glad you found it
Feb 25 '07 #5

Post your reply

Sign in to post your reply or Sign up for a free account.