Purpose of size_t

closed account (4ET0pfjN)
Hi, I just found out C++ supports vectors which I guess are safer to use than dynamiically allocated memory for arrays, but what is size_t in the for loop, why not just a regular int i = 0 for the intialized value in for loop?

Also, what's with the flush? Man, there are a lot of these little things in C++ or programming in general...

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <vector>
using namespace std;
 
int main()
{
    vector<double> student_marks(20);
 
    for (vector<double>::size_type i = 0; i < 20; i++)
    {
        cout << "Enter marks for student #" << i+1 
             << ": " << flush;
        cin >> student_marks[i];
    }
    // ... Do some stuff with the values
 
    return 0;
}
Last edited on
size_t is the type returned by the sizeof operator, and it's what you're supposed to be using as index for *arrays*. In this program, the loop uses vector<double>::size_type, correctly.

flush is completely redundant because the very next line calls cout.flush() before doing anything else.
Last edited on
closed account (3hM2Nwbp)
1) What's size_type?

std::vector::size_type is a type that is defined in the vector class. It is an "unsigned integral type", per the documentation.

2) What's flush?

It's a bit harder to explain in a simple sentence. Here's a page explaining it.

http://www.cplusplus.com/reference/iostream/manipulators/flush/

There are quite a few things in the standard C++ library that are "left as an exercise to the reader". I personally find that notion horrifying.
Last edited on
Topic archived. No new replies allowed.