



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.
*v_itr = 3.14; cout << *s_itr << endl; *l_itr = "Hello";
In the first and third lines, *v itr and *l itr are l-values. In the second, *s_itr is an r-value.
list
list
p = v.erase(p);
Write a function that takes a list of integers, lst, and an integer, x. The function should 1) remove all negative numbers from the list, 2) verify that the remaining elements in the list are sorted in increasing order, and 3) insert x into the list such that the order is maintained.
#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; }