//example15.cpp vector<int> vec = {1, 2, 3, 4, 5, 6}; for_each(vec.begin(), vec.end(), [](int &item) -> void { cout << item << " ";item++; }); cout << endl; // 1 2 3 4 5 6 for_each(vec.begin(), vec.end(), [](int &item) -> void { cout << item << " "; }); cout << endl; // 2 3 4 5 6 7
时间: 2024-04-15 10:26:15 浏览: 100
这段代码使用了 `for_each` 算法来遍历一个整数向量 `vec` 中的元素,并对每个元素进行操作。首先,使用 Lambda 表达式作为参数传递给 `for_each` 算法的第三个参数,Lambda 表达式 `[&](int &item) -> void { cout << item << " "; item++; }` 接受一个整数的引用,并输出该整数,然后将其自增1。这样,输出的结果为 1 2 3 4 5 6。接着,再次调用 `for_each` 算法,并使用另一个 Lambda 表达式 `[&](int &item) -> void { cout << item << " "; }` 输出修改后的向量中的元素,此时输出结果为 2 3 4 5 6 7。
相关问题
in c++, how can I transfer the vector's element to the set
In C++, you can transfer elements from a `vector` to a `set` by iterating through the vector and inserting each element into the set individually. Here's a simple example:
```cpp
#include <iostream>
#include <vector>
#include <set>
int main() {
std::vector<int> vec = {10, 20, 30, 40, 50}; // Example vector
std::set<int> set; // Empty set to insert elements into
// Transfer elements from vector to set
for (const auto &element : vec) {
set.insert(element);
}
// Now, 'set' contains unique elements from the 'vec'
for (const auto &value : set) {
std::cout << value << " ";
}
std::cout << "\n";
return 0;
}
```
In this code, we use a range-based for loop (`for (const auto &element : vec)`), which automatically iterates over the elements of the `vector`. Each element is then inserted into the `set`, ensuring that there are no duplicates because sets only store unique elements.
阅读全文