容器迭代器是一种用于遍历容器中元素的对象
std::vector<int> vec = {1, 2, 3, 4, 5};
for (auto it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << " ";
}
std::vector<int> vec = {1, 2, 3, 4, 5};
for (const auto &element : vec) {
std::cout<< element << " ";
}
std::vector<int> vec = {1, 2, 3, 4, 5};
for (auto it = vec.rbegin(); it != vec.rend(); ++it) {
std::cout << *it << " ";
}
std::vector<int> vec = {1, 2, 3, 4, 5};
auto it = vec.begin();
std::cout << *std::next(it)<< std::endl; // 输出2
std::cout << *std::prev(std::next(it, 2))<< std::endl; // 输出1
std::vector<int> vec = {1, 2, 3, 4, 5};
auto it1 = vec.begin();
auto it2 = vec.begin() + 2;
std::cout<< std::distance(it1, it2)<< std::endl; // 输出2
std::vector<int> vec = {1, 2, 3, 4, 5};
auto it = vec.begin();
std::advance(it, 2);
std::cout << *it<< std::endl; // 输出3
std::list<int> lst = {1, 2, 3, 4, 5};
for (auto it = lst.begin(); it != lst.end();) {
if (*it % 2 == 0) {
it = lst.erase(it);
} else {
++it;
}
}
std::vector<int> vec = {1, 2, 3, 4, 5};
auto it = std::find(vec.begin(), vec.end(), 3);
if (it != vec.end()) {
std::cout << "Found: " << *it<< std::endl;
} else {
std::cout << "Not found"<< std::endl;
}
std::set<int> s = {1, 2, 3, 4, 5};
auto lb = std::lower_bound(s.begin(), s.end(), 3);
auto ub = std::upper_bound(s.begin(), s.end(), 3);
auto er = std::equal_range(s.begin(), s.end(), 3);
std::vector<int> vec = {1, 2, 3, 4, 5};
std::for_each(vec.begin(), vec.end(), [](int x) { std::cout << x << " "; });
这些技巧可以帮助你更有效地使用容器迭代器。请注意,这里给出的示例主要针对C++标准库容器,但许多技巧也适用于其他容器类型。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。