#include <iostream>
#include <forward_list>
int main() {
// 创建一个空的 forward_list
std::forward_list<int> myForwardList;
// 在 forward_list 开头插入元素
myForwardList.push_front(10);
myForwardList.push_front(20);
myForwardList.push_front(30);
// 遍历 forward_list 并打印元素
std::cout << "Forward list elements:";
for (int x : myForwardList) {
std::cout << " " << x;
}
std::cout << std::endl;
// 在第一个元素后插入一个新元素
auto it = myForwardList.begin();
myForwardList.insert_after(it, 15);
// 再次遍历 forward_list 并打印元素
std::cout << "Forward list elements after insertion:";
for (int x : myForwardList) {
std::cout << " " << x;
}
std::cout << std::endl;
// 删除第一个元素
myForwardList.pop_front();
// 打印 forward_list 的大小
std::cout << "Forward list size after popping: " << std::distance(myForwardList.begin(), myForwardList.end()) << std::endl;
return 0;
}
#include <iostream>
#include <forward_list>
#include <algorithm> // 包含 std::find 算法函数
int main() {
// 创建一个 forward_list
std::forward_list<int> myForwardList = {10, 20, 30, 40, 50};
// 查找元素 30
auto it = std::find(myForwardList.begin(), myForwardList.end(), 30);
// 检查是否找到元素
if (it != myForwardList.end()) {
std::cout << "Element 30 found in the forward_list" << std::endl;
} else {
std::cout << "Element 30 not found in the forward_list" << std::endl;
}
return 0;
}
查找元素