Working With Vectors
Working With Vectors
In [ ]: # include <iostream>
# include <vector>
using std::vector;
using std::cout;
int main() {
vector<int> a = {0, 1, 2, 3, 4};
cout << a[0];
cout << a[1];
cout << a[2];
cout << "\n";
}
Run Code
Loading terminal (id_3x3ju6v), please wait...
Great! Now try accessing some of the elements of vector a yourself in the cell bellow:
In [ ]: # include <iostream>
# include <vector>
using std::vector;
using std::cout;
int main() {
vector<int> a = {0, 1, 2, 3, 4};
// Add some code here to access and print elements of a.
cout << "\n";
}
Run Code
Show Solution
Loading terminal (id_za35048), please wait...
1
If you tried to access the elements of a using an out-of-bound index, you might have noticed
that there is no error or exception thrown. If you haven’t seen this already, try the following code
in the cell above to see what happens:
In this case, the behavior is undefined, so you can not depend on a certain value to be returned.
Be careful about this! In a later lesson where you will learn about exceptions, we will discuss other
ways to access vector elements that don’t fail silently with out-of-range indices.
In [ ]: # include <iostream>
# include <vector>
using std::vector;
using std::cout;
int main() {
vector<vector<int>> b = {{1, 1, 2, 3},
{2, 1, 2, 3},
{3, 1, 2, 3}};
}
Run Code
Show Solution
Loading terminal (id_cihsz4b), please wait...
In [ ]: # include <iostream>
# include <vector>
using std::vector;
using std::cout;
int main() {
vector<int> a = {0, 1, 2, 3, 4};
2
Run Code
Loading terminal (id_jzilsrt), please wait...
In [ ]: # include <iostream>
# include <vector>
using std::vector;
using std::cout;
int main() {
Run Code
Show Solution
Loading terminal (id_7gepq7h), please wait...
Nice work! You now know a little more about C++ vectors. After learning about for loops, you
should be well prepared for the upcoming code exercises.