Range Over Built in C++
For this example, we’ll translate the provided code to C++.
Range in C++ is typically done using iterators or range-based for loops. Here’s how the provided code would look in C++:
#include <iostream>
#include <vector>
#include <map>
int main() {
// Summing numbers in a vector
std::vector<int> nums = {2, 3, 4};
int sum = 0;
for (int num : nums) {
sum += num;
}
std::cout << "sum: " << sum << std::endl;
// Using index and value in a range-based loop
for (size_t i = 0; i < nums.size(); ++i) {
if (nums[i] == 3) {
std::cout << "index: " << i << std::endl;
}
}
// Iterating over a map
std::map<std::string, std::string> kvs = {{"a", "apple"}, {"b", "banana"}};
for (const auto& kv : kvs) {
std::cout << kv.first << " -> " << kv.second << std::endl;
}
// Iterating only over the keys of the map
for (const auto& kv : kvs) {
std::cout << "key: " << kv.first << std::endl;
}
// Iterating over a string's characters
std::string str = "go";
for (size_t i = 0; i < str.size(); ++i) {
std::cout << i << " " << static_cast<int>(str[i]) << std::endl;
}
return 0;
}
Here’s the detailed explanation adapted for C++:
Our first example uses a loop to sum the numbers in a vector. Arrays work like this too.
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {2, 3, 4};
int sum = 0;
for (int num : nums) {
sum += num;
}
std::cout << "sum: " << sum << std::endl;
return 0;
}
To run this program, put the code in main.cpp
and compile it using a C++ compiler.
$ g++ -o main main.cpp
$ ./main
sum: 9
In the next example, we use a loop to print the indexes.
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums = {2, 3, 4};
for (size_t i = 0; i < nums.size(); ++i) {
if (nums[i] == 3) {
std::cout << "index: " << i << std::endl;
}
}
return 0;
}
To run this code, compile and execute in the same way as before.
To iterate over a map:
#include <iostream>
#include <map>
int main() {
std::map<std::string, std::string> kvs = {{"a", "apple"}, {"b", "banana"}};
for (const auto& kv : kvs) {
std::cout << kv.first << " -> " << kv.second << std::endl;
}
return 0;
}
Also, you can iterate over just the keys of a map.
#include <iostream>
#include <map>
int main() {
std::map<std::string, std::string> kvs = {{"a", "apple"}, {"b", "banana"}};
for (const auto& kv : kvs) {
std::cout << "key: " << kv.first << std::endl;
}
return 0;
}
Lastly, to iterate over the characters of a string and get their Unicode code points:
#include <iostream>
#include <string>
int main() {
std::string str = "go";
for (size_t i = 0; i < str.size(); ++i) {
std::cout << i << " " << static_cast<int>(str[i]) << std::endl;
}
return 0;
}
Compile and run each of these examples using your C++ compiler to see the output. Now that we can run and build basic C++ programs, let’s learn more about the language.