【问题标题】:Using substr to find nearby characters使用 substr 查找附近的字符
【发布时间】:2016-04-16 07:56:25
【问题描述】:

所以我试图找到距离我正在迭代的每个字符 X 距离内的字符。举个例子....

nearby("abcdefg", 2)

应该返回一个集合,每个字符作为一个键,它的值在 2 的距离内接近。它应该看起来像这样......

dictionary('a' -> set(a, b, c), 'b' -> set(a, b, c, d), 'c' -> set(a,b,c,d,e))

我的代码现在看起来像这样......

dictionary<char, set<char>> near(const std::string word, int dist) {
    dictionary<char, set<char>> map;
    for (int x = 0; x < word.size(); x++) {
        for (char letter : word.substr(std::max(0, x - dist), std::min(dist + 1, int(word.size()))))
            map[word[x]].insert(letter);
    }
    return map;
}

问题概述: - 它在大多数情况下都有效,但是,由于 C++ 的子字符串,我无法指定我想要索引 0 到 4 的所有字符。相反,它的索引为 0,然后包含 4 范围内的任何内容。这是有问题的当我想向后包含字符 4 个字母在前面 在后面。

到目前为止,我的代码将是正确的,但在最后留下一个字符。所以它看起来像这样......

nearby(abcdefg, 2)
dictionary('c' -> set(a,b,c))

省略了 d。

【问题讨论】:

  • 这个类的“字典”是什么?只是std::map吗?如果是这样,请写下来。此外,您指的是std::min,但只是set。是std:set 吗?如果不是,那是什么?
  • 我想你可以假设;它们是我制作的自定义类,但我认为这与问题本身无关。只知道他们操作字典和集合的方式正常工作。他们工作正常;问题是字符串的拼接。

标签: c++ splice


【解决方案1】:

你只需要:

        const auto start = std::max(0, x-dist);
        const auto end = std::min(x+dist+1, int(word.size());
        const auto len = end - start;
        const auto substring = word.substr(start,len);
        auto &the_set = map[word[x]];
        for (const auto letter : substring)
            the_set.insert(letter);

如 cmets 中所述,如果 word.size() > INT_MAX,这将中断。解决方案是在size_t 中做所有事情(你可以std::string::size_t 中做所有事情,但这太冗长了,而且并没有真正为你买任何东西)。

dictionary<char, set<char>> near(const std::string word, size_t dist) {
    dictionary<char, set<char>> map;
    for (size_t x = 0; x < word.size(); x++) {
        const auto start = (x > dist) ? x-dist : 0;  // Beware underflow
        const auto end = std::min(x+dist+1, word.size());
        const auto len = end - start;
        const auto substring = word.substr(start,len);
        auto &the_set = map[word[x]];
        for (const auto letter : substring)
            the_set.insert(letter);
     }
 }

这个版本的优点是 gcc 会用 -Werror -Wall 编译它(以前的版本会抱怨有符号/无符号比较),并且没有强制转换(总是一个好兆头)。

更好的版本是startendword 的迭代器——此时你根本不需要创建子字符串(你可以看看在原词中的字符处)。

【讨论】:

  • 我第二喜欢的关键字是auto;我最喜欢的是const。你永远猜不到吧?
  • std::min(x+dist+1, int(word.size()); 如果std::string::size_type 的最大值大于int,则会中断
  • 我认为它实际上只会在 word.size() 大于 INT_MAX 时才会中断(这显然只有在 std::string::size_type 的最大值大于 int 时才有可能,但条件要强得多)。破损也存在于原始代码中。
  • 你真是太高兴了。我因为没有提出长度差异而感到很愚蠢。我一直在尝试做一些拼接操作。
  • @MartinBonner 是的,这是正确的。我的意思是,如果std::string::size_type 可以保存大于int 的值,那么如果string.size() &gt; INT_MAX
猜你喜欢
  • 2015-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-10-08
  • 2019-04-21
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
相关资源
最近更新 更多