您好,登錄后才能下訂單哦!
容器迭代器是一種用于遍歷容器中元素的對象
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進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。