Code clarification (Easy question)

I am going through some undocumented code and I am trying to figure out what this is doing (modified for simplicity):

1
2
3
4
5
string myArray[] = {"one","two","three","four",""};
vector<string> myVector = vector<string>(myArray, myArray + sizeof(myArray) / sizeof(string));
myStr = "";
for(int i = 0; i < (int)myVector.size() - 1; i++)
  myStr += (i!=0? ", ":"") + myVector[i];


I have a couple of questions.

1. What does line 2 do? I looked at the constructors for the Vector class and don't know what's going on with the second parameter.

2. Why do I need the vector? Can't I create myStr from the array? It looks like much more code than is needed (myVector is never used again).

3. General question about vectors, why does the size need to be casted? Looking at the class definition, I see that it returns type "size_type," but why would that not always be an integer?
1. line 2 is using iteration constructor:
template <class InputIterator> vector ( InputIterator first, InputIterator last, const Allocator& = Allocator() );
Iteration constructor: Iterates between first and last, setting a copy of each of the sequence of elements as the content of the container.

So, the first parameter is a pointer pointing to the first element in the array. the second parameter is a pointer pointing to the end of the array.

2. For sure in your case, you can create myStr from the array, and you don't need the vector except you want to have fun with it. I guess the vector is used here because its coder might want to use it in the future, or just leave it for a while, this situation always happens in industry.

3. casting size() to int is for making compiler happy, otherwise some compilers will output a warning about you are comparing signed value with unsigned value.
In order to make cross-platform STL, size_type is used so that it would be replaced by proper native types on different platforms. size_type is indeed an integer but it's normally unsigned.
In C/C++ world, integer is classified to 2 types, signed and unsigned, some smart compilers are sensitive on handling these types so that to help programmer producing less bugs...
If you read STL's header files, you will find out that size_type is a typedef type.
3. If you don't want that warning, then don't enable it.
I think it would be better to use for( size_t K=0; K+1 < v.size(); ++K) instead
Topic archived. No new replies allowed.