Tuples

Tuples - motivation

Suppose we want to create a function returning three statistic values for a vector of integers:

  • minimum value
  • maximum value
  • average value

@css[fragment](Problem – the function can return only one value)

Solution 1

Passing parameters by reference

void calculate_stats(const vector<int>& data, int& min, int& max, double& avg)
{
    min = *min_element(data.begin(), data.end());
    max = *max_element(data.begin(), data.end());
    avg = accumulate(data.begin(), data.end(), 0.0) / data.size();
}

vector<int> data = {42, 11, 55, 665, 13, 2, 1024};

int min, max;
double avg;

calculate_stats(data, min, max, avg);

Solution 2

Passing parameters by reference

std::tuple<int, int, double> calculate_stats(const vector<int>& data)
{
    auto min = *min_element(data.begin(), data.end());
    auto max = *max_element(data.begin(), data.end());
    auto avg = accumulate(data.begin(), data.end(), 0.0) / data.size();

    return std::make_tuple(min, max, avg);
}

vector<int> data = {42, 11, 55, 665, 13, 2, 1024};

int min, max;
double avg;

std::tie(min, max, avg) stats = calculate_stats(data);

Constructing a tuple

  • Default constructor constructs a tuple object with its elements value-initialized:
std::tuple<short, std::string> two_items;
assert(std::get<0>(two_items) == 0);
assert(std::get<1>(two_items) == ""s);

Constructing a tuple

  • Constructor with parameters:
std::tuple<int, double, std::string> triple{42, 3.14, "Test krotki"};

deck

By Krystian Piękoś