Compiling C++TopWhy C++Arrays and strings

Arrays and strings

Standard C holds strings as arrays of char. Don't use them. Instead use string (which must be included). Strings are mutable and you can access and update characters with array notation: myStr[3]. Ordering works with <, >, <=, etc., using dictionary ordering.

Just say no to arrays! Experienced C++ programmers apparently avoid arrays like the plague. Reasons include difficulty in memory management, the need to keep track of size independently (i.e., no length attribute), and the lack of bounds checking. Use vector instead. It works like ArrayList in Java. See vectorExample.

Notice that push_back = add in Java, but [] or the method "at" can be used to access an element at a particular index. That is, we could write v[3] or v.at(3). Assignments can be made directly with v[i] = newVal; as long as i is within the range of existing indices. Vectors can be declared with no size parameter or with them. E.g.

    vector<string> myVect(6);  // initial size of 6
    vector<string> myVect;   // initially of size 0.

There is no need to create the vector with a "new" statement.


Compiling C++TopWhy C++Arrays and strings