The University of Iowa
The College of Liberal Arts and Sciences
Department of Computer Science
Programming Languages and Tools:
CS:3210:0001
Lecture/Lab #16
Programming with C++
std::vector, file input/output
Warm up
struct wave
{
virtual double wavelength() const = 0;
virtual double amplitude() const = 0;
virtual double frequency() const = 0;
};
struct particle
{
virtual double size() const = 0;
virtual double mass() const = 0;
};
struct light : wave, particle { ... };
void do_wave_stuff( wave& );
void do_particle_stuff( particle& );
int main() {
light l;
do_wave_stuff( l );
do_particle_stuff( l );
}
std::vector
#include <vector>
int main() {
std::vector<point> v = {
point{ 0, 0 },
point{ 10, 17 },
point{ 5, -7 }
};
std::cout << v.size() << std::endl;
}
-
A linear collection of objects, all of which have the same type
-
Often referred to as a container because it “contains” other objects.
-
Similar to list in Python / ArrayList in Java
-
Every object in vector has an associated index, which gives access to that object.
Exercise 1
Write a program that asks user for a number N, then asks user to enter N integers, then prints the space-separated sequence of integers to the console
-
Open the exercise template
-
Write your code, press Run to test
-
When you're done, grab your Repl's link and send it as a direct message to me (agurtovoy)
-
Click on the corresponding option in the "Lab16 exercises" poll in #general
File input/output
- We already know how to write to/read from a file:
#include <iostream>
#include <fstream>
void hello( std::ostream& out )
{
out << "Hello, world!" << std::endl;
}
int main()
{
std::ofstream out( "hello.txt" );
hello( out ); // save greeting to file
hello( std::cout ); // print greeting to console
}
I/O streams hierarchy
#include <ios>
#include <ostream>
#include <istream>
#include <fstream>
#include <sstream>
#include <iostream>
cin, cout, cerr, clog
I/O error handling
int main()
{
int n = 0;
std::cin >> n; // no error handling
int m;
if ( std::cin >> m ) // check for errors
std::cout << m;
else
std::cout << "Error reading from stream\n";
}
Programming with C++, Fall 2019, Lecture #16
By Aleksey Gurtovoy
Programming with C++, Fall 2019, Lecture #16
std::vector, file input/output
- 449