-3

I am trying to understand a part of a code in which

(*this).bond.assign(mck.bond.begin(), mck.bond.end())

I want to understand the role of begin() and end () command. I read at different places that it is an iterator index but i couldn't understand its meaning. I tried to understand it by writing a short code but it is not working. Can someone please help me to understand the above line of the code and the role of begin() and end() command.

int main()
{
  vector<int> vec_name;

  vec_name.push_back(10);
  vec_name.push_back(20);
  vec_name.push_back(30);
  vec_name.push_back(40);

  cout << vec_name.size() <<endl;
  cout << vec_name.begin() <<endl;
}
pergy
  • 5,285
  • 1
  • 22
  • 36
rida
  • 41
  • 5
  • 1
    Have you looked at the [documentation](http://www.cplusplus.com/reference/vector/vector/begin/)? One tip, you should dereference `vec_name.begin()` if you want to access the first element's value. – frslm Oct 31 '17 at 14:38
  • 1
    There's a good list of books [here](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – molbdnilo Oct 31 '17 at 14:38
  • 2
    @frslm actually you should use `front()` instead. – Slava Oct 31 '17 at 14:43
  • also, the documentation of [assign](http://en.cppreference.com/w/cpp/container/vector/assign) is useful. Your case is (2). – pergy Oct 31 '17 at 14:44

1 Answers1

1

.begin() returns an iterator, not the element or a reference to the element. It's not the same as printing vec_name[i] or using vec_name::front() which returns a reference. So to print the returned value, you need to declare an iterator which receives the return value of vec_name.begin() and then print the iterator.

**EDIT: ** Using your example code, it would be something like this:

int main()
{
  vector<int> vec_name;
  vector<int>::iterator it;

  vec_name.push_back(10);
  vec_name.push_back(20);
  vec_name.push_back(30);
  vec_name.push_back(40);

  cout << vec_name.size() <<endl;
  //cout << vec_name.begin() <<endl; //cannot print iterators directly
  it = vec_name.begin();  //Pass return value to iterator.
  cout << *it << endl;    //Print dereferenced iterator 

}
Javia1492
  • 862
  • 11
  • 28
  • 2
    @rida I suggest reading up on what an iterator is. That should clarify your confusion because that's at the core functionality of `.begin()`. http://www.cplusplus.com/reference/iterator/ – Javia1492 Oct 31 '17 at 16:01