for (... : items)This is a range-based for loop (introduced in C++11).
#include <iostream>
#include <vector>
#include <algorithm> // for std::sort
int main() {
std::vector<int> numbers = {5, 2, 9, 1, 5, 6};
std::sort(numbers.begin(), numbers.end());
for (int n : numbers)
std::cout << n << " ";
}
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {10, 20, 30, 40};
auto it = std::find(v.begin(), v.end(), 30);
if (it != v.end())
std::cout << "Found: " << *it << std::endl;
else
std::cout << "Not found" << std::endl;
}
std::find algorithm in C++ (from ) searches for the first occurrence of a given value in a range.
What *it Means- In C++, iterators behave like pointers.- it itself is an iterator object (not the actual element).- Using *it dereferences the iterator, giving access to the element it points to.
it → an iterator pointing to the element 20.*it → the actual value stored at that position (20).Why Not Just Use it?
- it is not the element, it’s a “cursor” pointing to the element.
- Printing it directly won’t give the value; it would try to print the iterator object (which usually doesn’t make sense).
- You need *it to access the contents.
Analogy
Think of an iterator like a TV remote:
- The remote (it) points to a channel.
- Dereferencing (*it) is like pressing the button to actually watch the channel.
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {1, 2, 3, 2, 4, 2};
int c = std::count(v.begin(), v.end(), 2);
std::cout << "Number of 2s: " << c << std::endl;
}
Microsoft Copilot
沒有留言:
發佈留言