From cd379d9e9eff734ae02708ba986b0fde1fa52d33 Mon Sep 17 00:00:00 2001 From: Mario Date: Tue, 12 Sep 2017 10:21:23 +0200 Subject: [PATCH] [c++/en] container -> vector (#2838) * container -> vector fixed errors: - "vector_name" and "Vector_name" (different case) would have resulted in a compile time error, now: "my_vector" enhancements: - typedef for consistency - two push_backs to show its purpose - both iteration types now have a working execution block (both output the vector's content) - the first "classic loop" now also shows the operator [], which therefor is removed from below - include and for with a white spaces for readability * removed the typedef the `typedef` was used to show that we will be using `string` as our base for all operations, but we are free to use any other type; of course it is technically not needed and might look like a redundancy. the two `cin` also look redundant, so I changed this into one `cin` and two `push_back`s --- c++.html.markdown | 30 +++++++++++++++--------------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/c++.html.markdown b/c++.html.markdown index 23013410..8d1c7a26 100644 --- a/c++.html.markdown +++ b/c++.html.markdown @@ -1000,24 +1000,24 @@ cout << get<5>(concatenated_tuple) << "\n"; // prints: 'A' // Vector (Dynamic array) // Allow us to Define the Array or list of objects at run time -#include -vector Vector_name; // used to initialize the vector +#include +string val; +vector my_vector; // initialize the vector cin >> val; -Vector_name.push_back(val); // will push the value of variable into array +my_vector.push_back(val); // will push the value of 'val' into vector ("array") my_vector +my_vector.push_back(val); // will push the value into the vector again (now having two elements) -// To iterate through vector, we have 2 choices: -// Normal looping -for(int i=0; i::iterator it; // initialize the iterator for vector -for(it=vector_name.begin(); it!=vector_name.end();++it) - -// For accessing the element of the vector -// Operator [] -var = vector_name[index]; // Will assign value at that index to var +// To iterate through a vector we have 2 choices: +// Either classic looping (iterating through the vector from index 0 to its last index): +for (int i = 0; i < my_vector.size(); i++) { + cout << my_vector[i] << endl; // for accessing a vector's element we can use the operator [] +} +// or using an iterator: +vector::iterator it; // initialize the iterator for vector +for (it = my_vector.begin(); it != my_vector.end(); ++it) { + cout << *it << endl; +} // Set // Sets are containers that store unique elements following a specific order.