troubleshooting Question

2nd argument to copy algorithm in STL c++

Avatar of Pra Sys
Pra SysFlag for India asked on
11 Comments3 Solutions406 ViewsLast Modified:
I have this simple basic code which inserts array of strings in to vector of strings. This was written for purpose of test program.

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <iterator>

using namespace std;

int main()
    vector<string> strVec;

    string arr[4] = {"Foo","Bar","Baz","Bee"};
    copy(&arr[0], &arr[4], back_inserter(strVec));
    copy(strVec.begin(),strVec.end(),ostream_iterator<string>(cout, "\n"));
    return 0;

In the first use of "copy" above, why STL copy algorithm takes 2nd argument as an address of 5th element of array "arr" when it doesn't exists and how it actually treats it legally internally? Why such an "illegal" (it appears that way) arrangement is allowed?? Without that it copies one element less in to the vector. I could not find any explanation anywhere so would appreciate. Why cant it take address of last element i.e. &arr[3]??
Join our community to see this answer!
Unlock 3 Answers and 11 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 3 Answers and 11 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros