You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++中从std::set提取满足多条件含'A'字符串的实现疑问

问题与解决方案

需求说明

给定存储在std::set中的单词集合(BELLOW, CELLO, HAAF, HABIT, HADAL, HAIR, HELLO, HELP, RABIT),需要完成以下三步操作:

  • 提取第0位索引为'H'的单词到新的std::set,结果为:HAAF, HABIT, HADAL, HAIR, HELLO, HELP
  • 从上述容器中提取第1位索引为'A'的单词,结果为:HAAF, HABIT, HADAL, HAIR
  • 从第二步的结果中,提取**除第0、1位索引外其他位置包含'A'**的单词,预期结果为:HAAF, HADAL

现有代码

#include <iostream>
#include <set>

int main()
{
    std::set<std::string> words = {"BELLOW", "CELLO",  "HAAF", 
                                   "HABIT",  "HADAL", "HAIR",
                                   "HELLO", "HELP", "RABIT"};
    for (const std::string& s : words) {
        std::cout << s << std::endl;    
    }
    
    std::set<std::string> etr;
    
    /* 提取以'H'开头的单词 */
    for (const std::string& s : words) {
        if (s[0] == 'H') {
           etr.insert(s);
        }
    }
    
    std::cout << std::endl;
    
    for (const std::string& s : etr) {
        std::cout << s << std::endl;    
    }
    
    std::set<std::string> etr2;
    
    /* 提取以'H'开头且第二位为'A'的单词 */
    for (const std::string& s : etr) {
        if (s[1] == 'A') {
           etr2.insert(s);
        }
    }
    
    std::cout << std::endl;
    
    for (const std::string& s : etr2) {
        std::cout << s << std::endl;    
    }
    
    /* 提取以'H'开头、第二位为'A',且其他位置包含'A'的单词 */
    // << 此处未实现 >>    
      
    return 0;
}

第三步实现方案

要实现第三步,需遍历第二步得到的etr2容器,检查每个单词中除第0、1位外的位置是否存在字符'A'。以下是修正后的可运行代码:

#include <iostream>
#include <set>
#include <algorithm>

int main()
{
    // 前两步代码与现有代码一致,此处省略
    
    std::set<std::string> etr3;
    // 定义需要排除的索引位置:0和1
    std::set<size_t> exclude_pos = {0, 1};

    /* 提取第0位是'H'、第1位是'A',且其他位置包含'A'的单词 */
    for (const std::string& s : etr2) {
        size_t occ = s.find('A');
        // 遍历所有'A'的出现位置
        while(occ != std::string::npos) {
            // 如果当前'A'的位置不在排除列表中,说明符合条件
            if (exclude_pos.find(occ) == exclude_pos.end()) {
                etr3.insert(s);
                break; // 找到一个符合条件的位置即可,无需继续遍历
            }
            // 查找下一个'A'的位置
            occ = s.find('A', occ + 1);
        }
    }

    // 输出结果
    std::cout << std::endl;
    for (const std::string& s : etr3) {
        std::cout << s << std::endl;    
    }
      
    return 0;
}

代码逻辑说明

  1. 定义exclude_pos集合存储需要排除的索引(0和1),避免在这两个位置检查'A';
  2. 对每个单词,用std::string::find遍历所有'A'的出现位置;
  3. 一旦找到不在排除列表中的'A'位置,就将该单词加入结果集etr3,并跳出循环(无需检查后续位置);
  4. 最终etr3中就是符合要求的单词:HAAF、HADAL。

内容的提问来源于stack exchange,提问作者Rose

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 08:06:19