



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




string a = "Tommy"; string b = a; // a new string is created using the string copy constructor string& c = a; // c is an alias/referece to the string object a
b[1] = ’i’; cout << a << " " << b << " " << c << endl; // outputs: Tommy Timmy Tommy
c[1] = ’a’; cout << a << " " << b << " " << c << endl; // outputs: Tammy Timmy Tammy
The reference variable c refers to the same string as variable a. Therefore, when we change c, we change a.
class Student { public: const string& first_name() const { return first_name_; } const string& last_name() const { return last_name_; } // etc....
private: string first_name_; string last_name_; // etc... };
vector
Based on our discussion of references above and looking at the class declaration, what if we wrote:
string & fname = students[i].first_name(); fname[1] = ’i’
Would the code then be changing the internal contents of the i-th Student object?
const string & fname = students[i].first_name(); fname[1] = ’i’
Then compiler would complain that you are trying to change a const object.
array/vector:
7 5 8 1 9 7 5 8 1 9 0 1 2 3 4
list:
vector
v_itr = vec.begin() + i; // i-th location in a vector l_itr = lst.begin(); // first entry in a list s_itr = str.begin(); // first char of a string
Note: We can add an integer to vector and string iterators, but not to list iterators.
list
list
p = v.erase(p);
#include using namespace std;
int main() {
int n; cout << "Enter the upper bound on the set of primes you are interested in: "; cin >> n;
list
// Initialize with everything from 2 to n for (unsigned int i=2; i<=n; ++i) primes.push_back(i);
// p will indicate the current prime list
// step through primes list until it is exhausted while (p != primes.end()) {
// throw out all the numbers that are divisible by the current prime
}
// output out all the primes cout << primes.size() << " primes: " << endl; for (p = primes.begin(); p != primes.end(); p++) { cout << *p << " "; } cout << endl;
return 0; }