// This file contains some examples of vector manipulation and more examples // of string manipulation, this time passing proper parameters using const & // // some common vector operations: // v.push_back(n) append n to end of vector // v.empty() is v empty? // v.size() how many elements in v? // v[index] reference to value at given index // ==, != compares all values for equality #include #include #include using namespace std; // pre : 0 <= n < 256 // post: returns an 8-character string with the binary representation of n string binary_8(int n) { string result = ""; for (int i = 0; i < 8; i++) { result = static_cast('0' + n % 2) + result; n /= 2; } return result; } // pre : bits contains a sequence of bits (the characters 0 and 1) // post: returns the integer equivalent of the binary representation int from_binary(const string & bits) { int result = 0; for (int i = 0; i < bits.size(); i++) { result = result * 2 + bits[i] - '0'; } return result; } int main() { // examples of vector construction vector v1; // constructs an empty vector vector primes = {2, 3, 5, 7, 11}; // constructs vector with values vector v2 = primes; // independent copy of primes vector v3 = {"hi", "there"}; // vector of string values vector v4(10, 42); // constructs a vector with 10 42s vector v5(20); // constructs a vector of 20 0s vector v6(10, "hello"); // constructs a vector of 10 "hello"s vector v7(5); // constructs a vector of 5 empty strings string bits = binary_8(209); cout << bits << endl; cout << from_binary(bits) << endl; return 0; }