在C++中当需要对某个容器或数组进行遍历时我们可以使用以下语句,c将会被赋值为s中的元素
for(char c:s):
//s可以是任何满足条件的容器或数组
for(int c:s):
for(double c:s):
for(float c:s):
在C++中我们来区分std::vector numbers = {1, 2, 3, 4, 5};和std::int numbers[] = {1, 2, 3, 4, 5};区别。
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers = {1, 2, 3, 4, 5};
// 使用范围-based for循环遍历vector<int>
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
#include <iostream>
int main() {
int numbers[] = {1, 2, 3, 4, 5};
// 使用范围-based for循环遍历数组
for (int num : numbers) {
std::cout << num << " ";
}
return 0;
}
区别:
动态大小 vs. 静态大小:
std::vector numbers = {1, 2, 3, 4, 5};:std::vector是