C++查找最大元素与s.find()和s.insert()

题目描述:

m老师在学习字符串的时候,对于字符串中的最大字符很感兴趣。
因此他想对于输入的每个字符串,查找其中的ASCII码最大字母,在该字母后面插入字符串“(max)”。

输入描述

输入数据包括多个测试实例,第一行输入一个整数n表示样例个数。每个实例由一行长度不超过100的字符串组成,字符串仅由大小写字母构成。

输出描述

对于每个测试实例输出一行字符串,输出的结果是插入字符串“(max)”后的结果,如果存在多个最大的字母,就在每一个最大字母后面都插入"(max)"。

样例输入 1

2
abcdefgfedcba
xxxxx
样例输出 1

abcdefg(max)fedcba
x(max)x(max)x(max)x(max)x(max)

代码示例

#include <iostream>
#include <string>
using namespace std;

int main() {
   
   
    int n;
    cin >> n;
    cin.ignore(); // Ignore newline after reading n
    
    while (n--) {
   
   
        string s;
        getline(cin, s);
        
        // Find maximum ASCII character
        char max_char = '\0';
        for (char c : s) {
   
   
            if (c > max_char) {
   
   
                max_char = c;
            }
        }
        
        // Insert "(max)" after each occurrence of max_char
        int pos = 0;
        while ((pos = s.find(max_char, pos)
### C++ `std::unordered_set` 的 `find` 方法 `std::unordered_set` 是 C++ 中的一个关联容器,用于存储唯一的元素,并通过哈希表实现快速查找操作。其成员函数 `find(key)` 用于定位指定键值是否存在集合中。 以下是关于 `std::unordered_set::find` 的详细说明以及一个完整的代码示例: #### 函数签名 ```cpp iterator find(const key_type& key); const_iterator find(const key_type& key) const; ``` - 如果找到匹配的键,则返回指向该元素的迭代器。 - 如果未找到匹配的键,则返回 `end()` 迭代器[^1]。 #### 使用注意事项 为了使自定义类型能够作为 `std::unordered_set` 的键值,必须为其提供合适的哈希函数等于运算符重载。这通常通过特化标准命名空间中的模板类 `std::hash` 重载全局 `operator==` 来完成。 #### 示例代码 下面是一个简单的例子,展示如何使用 `std::unordered_set::find` 查找整数类型的键值: ```cpp #include <iostream> #include <unordered_set> int main() { std::unordered_set<int> mySet = {1, 2, 3, 4, 5}; int searchKey = 3; auto it = mySet.find(searchKey); if (it != mySet.end()) { std::cout << "Found: " << *it << std::endl; // 输出 Found: 3 } else { std::cout << "Not found!" << std::endl; } return 0; } ``` 对于更复杂的场景,比如自定义数据结构作为键值时,需额外定义哈希函数相等比较逻辑。例如: ```cpp #include <iostream> #include <string> #include <unordered_set> struct Person { std::string name; int age; bool operator==(const Person &other) const { return name == other.name && age == other.age; } }; namespace std { template <> struct hash<Person> { size_t operator()(const Person &p) const { return hash<std::string>()(p.name) ^ hash<int>()(p.age); // 自定义哈希组合 } }; } int main() { std::unordered_set<Person> people; people.insert({"Alice", 30}); people.insert({"Bob", 25}); Person searchPerson{"Alice", 30}; auto it = people.find(searchPerson); if (it != people.end()) { std::cout << "Found person: " << it->name << ", Age: " << it->age << std::endl; } else { std::cout << "Person not found." << std::endl; } return 0; } ``` 上述代码展示了当键为复杂对象时,如何正确配置哈希函数等于运算符以支持 `std::unordered_set::find` 功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值