re-formatting

This commit is contained in:
Jidong Xiao
2024-02-27 13:06:24 -05:00
parent 4b3fc146d5
commit b85a833952

View File

@@ -49,18 +49,23 @@ the less than comparison function for the type stored inside the container. How
```cpp ```cpp
bool float_less(float x, float y) { bool float_less(float x, float y) {
return x < y; return x < y;
} }
``` ```
- Remember how we can sort the my_data vector defined above using our own homemade comparison function - And then let's define a vector called *my_data*:
for sorting:
```cpp
std::vector<float> my_data = {1.1, 2.2, 3.3, 4.4, 5.5};
```
- Remember how we can sort the my_data vector defined above using our own homemade comparison function for sorting:
```cpp ```cpp
std::sort(my_data.begin(),my_data.end(),float_less); std::sort(my_data.begin(),my_data.end(),float_less);
``` ```
If we dont specify a 3rd argument: If we don't specify a 3rd argument:
```cpp ```cpp
std::sort(my_data.begin(),my_data.end()); std::sort(my_data.begin(),my_data.end());
@@ -81,7 +86,9 @@ of that class. Then, that instance/object can be used like its a function. We
template <class T> template <class T>
class less { class less {
public: public:
bool operator() (const T& x, const T& y) const { return x < y; } bool operator() (const T& x, const T& y) const {
return x < y;
}
}; };
``` ```
@@ -97,10 +104,12 @@ during computation of the function call operator! For example:
```cpp ```cpp
class between_values { class between_values {
private: private:
float low, high; float low, high;
public: public:
between_values(float l, float h) : low(l), high(h) {} between_values(float l, float h) : low(l), high(h) {}
bool operator() (float val) { return low <= val && val <= high; } bool operator() (float val) {
return (low <= val && val <= high);
}
}; };
``` ```
@@ -116,6 +125,7 @@ if (std::find_if(my_data.begin(), my_data.end(), two_and_four) != my_data.end())
std::cout << "Found a value greater than 2 & less than 4!" << std::endl; std::cout << "Found a value greater than 2 & less than 4!" << std::endl;
} }
``` ```
Alternatively, we could create the functor without giving it a variable name. And in the use below we also Alternatively, we could create the functor without giving it a variable name. And in the use below we also
capture the return value to print out the first item in the vector inside this range. Note that it does not print capture the return value to print out the first item in the vector inside this range. Note that it does not print
all values in the range. all values in the range.