for loop iterations in C++, Javascript, Python
for loop cheat sheet
C++
Range-based for loop over iterable
for ( range_declaration : range_expression )
loop_statement// Iterating over whole array
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
std::cout << i << ' ';// the initializer may be a braced-init-list
for (int n : {0, 1, 2, 3, 4, 5})
std::cout << n << ' '// Printing string characters
std::string str = "Poby";
for (char c : str)
std::cout << c << ' ';// Printing keys and values of a map
std::map <int, int> MAP({{1, 1}, {2, 2}, {3, 3}});
for (auto i : MAP)
std::cout << '{' << i.first << ", " << i.second << "}\n";
for_each
Applying a function to a range
void myfunction (int i) { // function:
std::cout << ' ' << i;
}
std::vector<int> v = {0, 1, 2, 3, 4, 5};
for_each (v.begin(), v.end(), myfunction);
Javascript
- for statement
- for … in statement
- for … of statement
for statement
for (let step = 0; step < 5; step++) {
// Runs 5 times, with values of step 0 through 4.
console.log('Walking east one step');
}
for … in statement
iterate over property names
const arr = [3, 5, 7];
arr.foo = 'hello';
for (let i in arr) {
console.log(i); // logs "0", "1", "2", "foo"
}
for … of statement
iterate over property values
const arr = [3, 5, 7];
arr.foo = 'hello';
for (let i of arr) {
console.log(i); // logs 3, 5, 7
}
Iterate through a Map
ES6
var myMap = new Map();
myMap.set("0", "foo");
myMap.set(1, "bar");
myMap.set({}, "baz");
for (const [key, value] of myMap.entries()) {
console.log(key, value);
}// 0 foo
// 1 bar
// {} baz
ES8
const object = {'a': 1, 'b': 2, 'c' : 3};
for (const [key, value] of Object.entries(object)) {
console.log(key, value);
}
// a 1
// b 2
// c 3
Python
loop over range
for x in range(0, 3):
print("We're
on time %d" % (x))
loop over iterable
string as an iterable
string = "Hello World"
for x in string:
print(x)
list as an iterable
collection = ['hey', 5, 'd']
for x in collection:
print(x)
loop over dictionary
print all keys
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
for x in thisdict:
print(x)// result
brand
model
year
print all values
for x in thisdict:
print(thisdict[x])// result
Ford
Mustang
1964
loop over value
use “values()”
for x in thisdict.values():
print(x)// result
Ford
Mustang
1964
loop over both keys and values
for x, y in thisdict.items():
print(x, y)// result
brand Ford
model Mustang
year 1964