-6

I am trying to display first element inserted into a vector.Can i use the begin() to access it?

 vector<int>s;
 s.push_back(5);
 cout<<s.begin();
mihir
  • 15
  • 5
  • 1
    Why not compile it and see? – Edgar Rokjān Jul 06 '17 at 16:53
  • 1
    If you want to know what the member functions do **[consult the reference](http://en.cppreference.com/w/cpp/container/vector)** – NathanOliver Jul 06 '17 at 16:54
  • Try to ran it.But gave me an error. – mihir Jul 06 '17 at 16:55
  • 3
    Do you know how to use *iterators*? Have you used iterators before, e.g. in a loop? Perhaps you should [find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) to read, because this is something that such a book would tell you. – Some programmer dude Jul 06 '17 at 16:56
  • 2
    You may be looking for [`std::vector::front`](http://en.cppreference.com/w/cpp/container/vector/front). – François Andrieux Jul 06 '17 at 16:58
  • 1
    "Try to ran it.But gave me an error." Well.. it's probably not valid then :p `std::vector::begin` returns an iterator, where the indirection operator is overloaded. `std::cout << *s.begin( );` – George Jul 06 '17 at 17:01
  • answer is No. [vector - begin](http://www.cplusplus.com/reference/vector/vector/begin/) and [what is an Iterator?](https://en.wikipedia.org/wiki/Iterator#C.2B.2B) – Jean-philippe Emond Jul 06 '17 at 17:05
  • Possible duplicate of [The difference between front() and begin()](https://stackoverflow.com/questions/9303110/the-difference-between-front-and-begin) –  Jul 06 '17 at 18:00

2 Answers2

0

In C++, the begin() member function returns a pointer (or iterator) to the front (a lot of the time, anyways).

You can access the first element with begin(), but you have to dereference it (like a pointer) first:

cout << *s.begin(); // 5

Here is a demo: https://repl.it/JQiU/0

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Chad K
  • 832
  • 1
  • 8
  • 19
0

Access with the std::vector::operator[].

vector<int>s;
s.push_back(5);
cout << s[0];
izaak_pyzaak
  • 930
  • 8
  • 23