Small Steps VI — Growing into C++

Adding elements and reading them one by one

Add elements and read them one by one.

What you will learn

std::vector lets you append elements. A range-based for visits a container's elements one at a time.

Try it

Example · example2.cpp
int sum(const std::vector<int>& numbers)
{
    int total = 0;

    for (int value : numbers)
        total = total + value;

    return total;
}

void small_main()
{
    std::vector<int> numbers = {10, 20, 30};
    numbers.push_back(40);

    print("Sum: ", sum(numbers));
}

push_back(40) appends 40. for (int value : numbers) receives each element's value in value and adds it to a total. The result is Sum: 100.

Here value is a copied integer, so changing it does not change an array element. size() may have a type different from int; check types when handling large sizes.

Exercise

Create text_length taking a const std::string& and returning its length. Print the length of "Small".

Exercise starter · exercise2_starter.cpp
int text_length(const std::string& text)
{
    // Return the length.
    return 0;
}

void small_main()
{
    std::string text = "Small";
    print(text_length(text));
}

Hint

text.size() returns a standard C++ unsigned size type. This exercise returns int, so explicitly convert with static_cast<int>(text.size()) before returning.

show solution
int text_length(const std::string& text)
{
    return static_cast<int>(text.size());
}

void small_main()
{
    std::string text = "Small";
    print(text_length(text));
}
← Previous lessonNext lesson →