Assuming that you are currently a reasonably skillful Java programmer, by the end of this course you should be able to
We will touch on the following features of C++:
Often C features coexist with newer, cleaner versions.
#include <iostream>
using namespace std;
int main() {
cout << "Hello world!\n";
return 0;
}
#include lines.
cout << "Hello world!\n";
int i;
cout << "Type a number: ";
cin >> i;
cout << i << " times 3 is " << (i*3) << '\n';
(((cout << i) << " times 3 is ") << (i*3)) << '\n';
#include <string>
The standard library provides a string type:
string s = "fred";
cout << s;
cin >> s; // reads a word
The + operator is overloaded on strings:
s = s + " and bill";
s = s + ',';
So are +=, ==, <, etc.
Unlike in Java, strings are modifiable:
s.erase(); // makes s empty
#include <string>
#include <iostream>
using namespace std;
int main() {
string s;
while (cin >> s)
cout << s << '\n';
return 0;
}
#include <vector>
C++ has arrays, but we'll use vectors instead:
vector<int> vi(5); // vector of 5 ints
vector<string> si; // empty vector of strings
Vectors can be accessed just like arrays:
vi[1] = x;
vi[2] = vi[1] + 3;
Vectors can also be extended:
si.push_back(s);
The current length of si is si.size()
string s1 = "bill", s2;
declares (and initializes) string objects, not pointers.
s1 = s2;
copy the objects.
string s1;
string s2 = "bill";
Objects are always initialized;
variables of primitive type aren't.
Assignment replaces an existing value:
s1 = s2;
Initialization defines a new variable:
string s3 = s2;
Formal parameters are new variables, initialized from actual parameters.
void f(int i) {
i = i + 5;
}
void g() {
int j = 3;
f(j); // no effect on j
}
A reference formal parameter is another name (an alias) for the actual parameter.
void f(int &i) {
i = i + 5;
}
void g() {
int j = 3;
f(j); // j is updated
}
Note:
There is no relationship to Java's references.
Reference parameters are also used to avoid copying large values:
int last(vector<int> &v) {
return v[v.size() - 1];
}
void g() {
vector<int> x(100);
...
int n = last(x); // don't copy x
}
We can indicate that the function doesn't change the parameter with the keyword const:
int last(const vector<int> &v) {
return v[v.size() - 1];
}
void g() {
vector<int> x(100);
...
int n = last(x); // don't copy x
}
This makes programs safer, and can help the compiler.
const int days_per_week = 7;
& after a type defines a reference,
which will be another name (or alias) for a piece of storage.
int x;
int &y = x;
y = 3;
is the same as assigning to x.
istream& getline(istream& in, string &s) {
s.erase();
char c;
while (in.get(c) && c != '\n')
s += c;
return in;
}
Note that
#include <iostream>
#include <string>
using namespace std;
int main() {
string s;
while (getline(cin, s))
cout << s.size() << '\t' << s << '\n';
return 0;
}