成员引用基本类型不是结构或联合

时间:2019-11-11 03:12:01

标签: c++ arrays

我需要一些作业上的帮助。

//finds frequency of a sequence in an array (including mutations)
int find_freq_with_mutations(string target,string sequences[],int sequences_length) {
    for (int i = 0; i < sequences_length; i++) { //goes through each sequence in array
        string current_sequence = sequences[i]; //sets current sequence as a string
        for (int j = 0; j < current_sequence.length(); j++) { //iterate for every character in sequence
            if (current_sequence[j] == current_sequence[j+1]) {
                current_sequence[j].erase();
            }
        }
    }
    int target_frequency = find_frequency(target, sequences, sequences_length);

    return target_frequency;

}

错误消息是:

DNA_sequencing.cpp:70:24: error: member reference base type
      'std::__1::basic_string<char, std::__1::char_traits<char>,
      std::__1::allocator<char> >::value_type' (aka 'char') is not a structure or
      union
                                current_sequence[j].erase();
                                ~~~~~~~~~~~~~~~~~~~^~~~~~

非常感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

读取代码显示表明您正在尝试在erase()中的某个字符上调用std::string。如果要删除字符串中的字符,则需要在erase()中调用std::string函数。我建议使用迭代器来遍历您的字符串,因为在要使用整数索引进行迭代的字符串上使用erase()函数会很困难,因为每次擦除字符串时,字符串中每个字符的索引都会改变字符。考虑到这一点,内部for循环变为:

for (auto it = current_sequence.begin(); it != current_sequence; ) {
      if (*it == *(it + 1)) {
           it = current_sequence.erase(it);
      } else {
           it++;
      }
}

另一个注意事项是,如果您打算对数组中的字符串进行突变,则您可能应该使用指针或引用,因为current_sequence只是数组中字符串的副本。由于您已经在使用数组,因此建议您遍历字符串指针本身,如下所示:

for (std::string *current_sequence = sequences; current_sequence < sequences + sequences_length; current_sequence++) {
    /* Do something with current_sequence */
}