Two-dimensional vectors

This lesson contains approximately 22 minutes of video content.

Two-dimensional std::vectors

Activity: Max subvector sum

Graded Playground Autograder

Activity Prompt:

In this problem, using the C++ conventions introduced in the daily lessons, you will declare a function named LargestVectorSum in the header file (solution.hpp) and define this function in the corresponding source file ( Your LargestVectorSum function must be defined with a single parameter, a two-dimensional std::vector of ints; this function will return an object typed LargestSumPair. We define this structured type (i.e., the function's return type) in largest-sum-pair.hpp; please do not change that definition. Now that the return type and signature of LargestVectorSum have been specified, let's discuss what this function is to do and how the returned object will be composed.

LargestVectorSum will examine the non-rectangular two-dimensional vector of integers passed to it subvector-by-subvector. For clarity:

std::vector<std::vector<int>> my_2d_vector{
      {1, 2, 4}, {4, 1, -1}, {6, 8, -10, -9}, {-1}}; // declares + initializes a non-rectangular 2D std::vector of ints;  // returns the subvector {1, 2, 4}
Your function will track the index into the subvector whose contents sum to the largest (most positive) integer value and record what that sum was. Keep in mind that the subvector may have positive and negative values. Since the two-dimensional vector is non-rectangular, you cannot assume that the subvectors contain an equal number of elements: the number of elements stored in one subvector can (and will) differ. If more than one subvector sums to the same value and that value is the largest sum, record the subvector with the smaller index. What does a smaller index mean? Given a two-dimensional vector indexed as, we mean the subvector residing at the smaller value of subvector_idx. Once you're finished examining the two-dimensional vector, create a new LargestSumPair object, initializing the data member index with the index to the subvector whose contents sum to the largest (most positive) integer value and sum with the sum calculated for that subvector. Assume the two-dimensional vector passed to your function will have at least one subvector.

Graded Files

Only the following files are transferred to the autograder.

  • solution.hpp
#include <vector> #include "solution.hpp" int main() { // std::vector<std::vector<int>> vect {{1, 2, 3, 4, 5}, // {84}, // {9, 10, 11, 12, 13, 14, 15}}; }
#ifndef SOLUTION_HPP #define SOLUTION_HPP #include <vector> #include "largest-sum-pair.hpp" #endif
#include "solution.hpp"
#ifndef LARGEST_SUM_PAIR_HPP #define LARGEST_SUM_PAIR_HPP #include <limits> struct LargestSumPair { unsigned int index = 0; int sum = std::numeric_limits<int>::min(); }; #endif