Small Steps VI — Growing into C++
Meeting standard strings and arrays
Meet standard strings and arrays.
What you will learn
A container holds several values. std::string and std::vector are standard tools corresponding to the strings and arrays you know.
Try it
Example · example1.cpp
void small_main()
{
std::string text = "Hello";
std::vector<int> numbers = {3, 7, 2, 9};
print(text);
print("Characters: ", text.size());
print("Numbers: ", numbers.size());
print("First number: ", numbers[0]);
}
The length operation is named size() instead of length(). The example prints Hello, Characters: 5, Numbers: 4, and First number: 3.
Bracket positions still start at 0. Do not expect standard containers' [] to report out-of-range errors the way Small does.
Exercise
Create a std::vector<int> containing 5 and 10, add another value with push_back(15), and print them all.
Exercise starter · exercise1_starter.cpp
void small_main()
{
std::vector<int> numbers = {5, 10};
// Add 15 and print every value.
}
Hint
Use a range-based for such as for (int value : numbers) to visit every value.
show solution
void small_main()
{
std::vector<int> numbers = {5, 10};
numbers.push_back(15);
for (int value : numbers)
print(value);
}