C++ foreach语法:如何使用foreach循环遍历数组和容器

发布时间:2023-05-24

一、foreach语法的基本知识

foreach循环在C++11中被引入。它允许我们简单明了地遍历数组,容器和其他带有迭代器的结构。 foreach循环的基本语法如下所示:

for (auto element : container)
{
    // 对 element 做一些操作
}

在这个语法中,auto关键字通常与元素类型推断一起使用,例如数组中的元素类型。 给定一个花费数组:

double costs[] = { 1.0, 2.0, 3.0 };

下面的foreach循环可以用于遍历数组:

for (auto cost : costs)
{
    std::cout << cost << std::endl;
}

循环将输出:

1
2
3

二、使用foreach循环遍历容器

我们可以使用foreach循环遍历C++容器。在这个例子中,我们可以使用std::vector容器:

std::vector<std::string> names = { "Tom", "Jerry", "Scooby" };
for (std::string name : names)
{
    std::cout << name << std::endl;
}

输出:

Tom
Jerry
Scooby

我们也可以使用auto关键字来推断数据类型:

std::vector<int> numbers = { 1, 2, 3, 4, 5 };
for (auto number : numbers)
{
    std::cout << number << std::endl;
}

输出:

1
2
3
4
5

三、使用foreach循环遍历字符串

我们可以不使用迭代器遍历字符串,而是使用foreach循环。在下面的例子中,我们将使用foreach循环遍历字符串:

std::string str = "Hello, world!";
for (char c : str)
{
    std::cout << c << std::endl;
}

输出:

H
e
l
l
o
,
w
o
r
l
d
!

四、使用foreach循环遍历结构体

我们可以使用foreach循环来遍历结构体数组。在下面的例子中,我们将使用foreach循环遍历结构体:

struct Employee{
    std::string name;
    int age;
};
Employee employees[] = { {"Tom", 28}, {"Jerry", 24}, {"Scooby", 26} };
for (auto e : employees)
{
    std::cout << "Name: " << e.name << ", Age: " << e.age << std::endl;
}

输出:

Name: Tom, Age: 28
Name: Jerry, Age: 24
Name: Scooby, Age: 26

五、foreach循环中使用引用

我们可以使用引用在foreach循环中改变集合中的元素。在下面的例子中,我们将使用foreach循环将std::vector中的元素全部修改为0:

std::vector<int> numbers = { 1, 2, 3, 4, 5 };
for (auto& number : numbers)
{
    number = 0;
}

现在,std::vector中的所有元素都变成了0:

0
0
0
0
0

六、foreach循环和const

我们也可以在foreach循环中使用const关键字,以确保我们不会在循环期间更改元素。 在下面的例子中,我们将使用const关键字来遍历std::vector

const std::vector<int> nums = { 1, 2, 3, 4, 5 };
for (const auto& number : nums)
{
    std::cout << number << std::endl;
}

输出:

1
2
3
4
5

七、总结

使用foreach循环是一种简单而又方便的方式来遍历数组,容器和其他带有迭代器的结构。它减少了代码的复杂度,并提高了可读性。可以在foreach循环中使用引用和const关键字。