@@ -172,3 +172,86 @@ vector <double> high_temperature (365, 80.0); // 365 initializes size of vecto
172
172
173
173
## Accessing and Modigying Vector Elements
174
174
175
+ ### Array syntax
176
+
177
+ - Same as arrays
178
+ - No bounds checking will be done
179
+
180
+ `vector_name [element_index]`
181
+
182
+ ```c++
183
+ vector <int> test_scores {100, 95, 99, 87, 88};
184
+
185
+ cout << "First score at index 0: " << test_scores[0] << endl;
186
+ cout << "Second score at index 1: " << test_scores[1] << endl;
187
+ cout << "Third score at index 2: " << test_scores[2] << endl;
188
+ cout << "Fourth score at index 3: " << test_scores[3] << endl;
189
+ cout << "Fifth score at index 4: " << test_scores[4] << endl;
190
+ ```
191
+
192
+ ### Vector syntax
193
+
194
+ - Created a vector, which is an ** object**
195
+ - Followed by the ** dot** (` . ` ) operator
196
+ - Followed by the ** method name** , name of the operation we want performed
197
+
198
+ ` vector_name.at(element_index) `
199
+
200
+ ``` c++
201
+ vector <int > test_scores {100, 95, 99, 87, 88};
202
+
203
+ cout << "First score at index 0: " << test_scores.at(0) << endl;
204
+ cout << "Second score at index 1: " << test_scores.at(1) << endl;
205
+ cout << "Third score at index 2: " << test_scores.at(2) << endl;
206
+ cout << "Fourth score at index 3: " << test_scores.at(3) << endl;
207
+ cout << "Fifth score at index 4: " << test_scores.at(4) << endl;
208
+ ```
209
+
210
+ ### Changing the contents of vector elements - vector syntax
211
+
212
+ - Similar to arrays
213
+
214
+ `vector_name.at(element_inded)`
215
+
216
+ ```c++
217
+ vector <int> test_scores {100, 95, 99, 87, 88};
218
+
219
+ cin >> test_scores.at(0);
220
+ cin >> test_scores.at(1);
221
+ cin >> test_scores.at(2);
222
+ cin >> test_scores.at(3);
223
+ cin >> test_scores.at(4);
224
+
225
+ // assignment statment
226
+ test_scores.at(0) = 90;
227
+ ```
228
+
229
+ - but can change size dynamically
230
+
231
+ `vector_name.push_back(element)`
232
+
233
+ ```c++
234
+ vector <int> test_scores {100, 95, 99}; // size is 3
235
+
236
+ test_scores.push_back(80); // size of 4: 100, 95, 99, 80
237
+ test_scores.push_back(90); // size of 5: 100, 95, 99, 80, 90
238
+ // vector will automatically allocate the required space!!!
239
+ ```
240
+
241
+ - What if you are out of bounds?
242
+ - Arrays never do bounds checking
243
+ - Many vector methods provide bound checking
244
+ - An exception and error message is generated
245
+
246
+ ```c++
247
+ vector <int> test_scores {100, 95};
248
+
249
+ cin >> test_scores.at(5);
250
+ ```
251
+ output error...
252
+
253
+ ```shell
254
+ terminate called after throwing an instance of 'std::out_of_range' what(): vector::_M_range_check: __n (which is 5) >= this->size() (which is 2)
255
+ This application has requested the Runtime to terminate it in an unusual way.
256
+ Please contact the applications support team for more infromation
257
+ ```
0 commit comments