10.3.1 Exercises Section
2025/10/18大约 2 分钟
10.3.1 Exercises Section
Exercise 10.12:
[!quote]
Write a function named compareIsbn that compares the isbn() members of two Sales_data objects. Use that function to sort a vector that holds Sales_data objects.
10.13
The library defines an algorithm named partition that ...
Write a function takes a string and returns a bool indicating whether the string has five characters or more. Use that function to partition words. Print the elements that have five or more characters.
10.12
inline
bool compareIsbn(const Sales_item &lhs, const Sales_item &rhs)
{
return lhs.isbn() == rhs.isbn();
return lhs.isbn() < rhs.isbn();
}ISBN:978-7-121-25529-7、978-7-5713-1166-7
特点:
- 数字 和 - 组成
- 由- 分隔为5组数字
这个具体ISBN到底要如何比较值不清楚,按照上面的ISBN看我觉得应该按照每组数字的大小进行比较。
源代码中使用 == , 习题参考中使用 <
但是这里重点不在于ISBN的比较,而是对容器内元素类型是类时,如何提供function 给 algorithm
10.13
标准库中定义的partition 算法的使用
std::vector<int> v{0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
std::cout << "Original vector: ";
for (int elem : v)
std::cout << elem << ' ';
auto it = std::partition(v.begin(), v.end(), [](int i) {return i % 2 == 0;});
std::cout << "\nPartitioned vector: ";
for (int elem : v)
std::cout << elem << ' ';
std::cout << std::endl;
std::cout << "*it:" << *it << "\n";
auto it2 = std::partition(v.begin(), v.end(), [](int i) {return i > 10; });
std::cout << (it2 == v.begin() ? true : false) << "\n";效果:
Original vector: 0 1 2 3 4 5 6 7 8 9
Partitioned vector: 0 8 2 6 4 5 3 7 1 9
*it:5
1将满足predicate(predicate 返回true)的元素排列到前面,不满足的元素排列到后面,并且返回指向最后一个predicate 返回 true 的元素的下一个位置(如果没有元素满足predicate 要求,那么返回指向第一个元素-和begin()指向相同)。
| 行号 | 功能 | 说明 |
|---|---|---|
| 6 | 对int 容器按照偶数在前奇数在后进行排列 | |
| 9-11 | 遍历打印排序后的容器 | |
| 13 | 打印算法返回的迭代器的指向元素值 | 5:指向第一个不满足predicate的元素 |
| 15 | predicate 条件为>10 | 容器中没有元素满足要求 |
| 16 | 判断返回迭代器的指向位置是否和容器的begin()指向相同 | 打印 1(true),表示两个迭代器指向相同。 |
实现:
bool five_or_more(const std::string &s)
{
return s.size() >= 5 ? true : false;
}
int main()
{
std::vector<std::string> v = {"1234", "123456", "789", "987654", "321", "45678"};
auto it = std::partition(v.begin(), v.end(), five_or_more);
std::cout << "*it:" << *it << "\n";
for(auto &s : v)
std::cout << s << " ";
std::cout << std::endl;
return 0;
}效果:
*it:789
45678 123456 987654 789 321 1234容器中”45678“排在最后,但是重新排序后排在最前。partition()不保证元素的相对顺序和排序前相同。