简体   繁体   中英

How does std::array bounds checking work?

I'm a little bit confused with std::array bounds checking.

Here's the code:

    const size_t studentResponses = 10; 
    const size_t surveyBound = 6;

    std::array<unsigned int, studentResponses> students{ 1, 3, 5, 5, 5, 4, 5, 4, 2, 2 };
    std::array<unsigned int, surveyBound> survey{}; //initializes it to '0'

    for (size_t answer = 0; answer < students.size(); ++answer) {
        ++survey[students[answer]];
    }

    std::cout << "Rating" << std::setw(12) << "Frequency" << std::endl;
    
    for (size_t rating = 1; rating < survey.size(); ++rating) {
        std::cout << std::setw(6) << rating << std::setw(12) << survey[rating] << std::endl;
    }

Output:

Rating   Frequency
 1           1
 2           2
 3           1
 4           2
 5           4

I've never used an array as a counter for another array. From what I understand by reading the book is that the value at 'n' element of students will become the value of survey's elemen, but when the output is displayed, that's where my confusion is.

  1. How is the array, survey , keeping a count of how many times of the value at of element in students is counted?
  2. Since the array survey is initialized to 6, how can it get the 10 values from students ?

My prof didn't really explain and just read it off a PowerPoint, so I'm trying to learn and understand it myself.

How is the array, survey , keeping a count of how many times of each element in students is counted?

By using this statement:

++survey[students[answer]];

Note that the students array must contain only values between 0 and 5 (inclusive). Then the value of students[answer] is used as an index into survey . The value at that index is then incremented.

Since the array survey is initialized to 6, how can it get the 10 values from students?

There are not 10, but only 6 positions in survey . Instead, the sum of all the values in survey will be equal to 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM