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

Member reference base type is not a structure or a union

本文关键字:结构 引用 基类 类型 成员      更新时间:2023-10-16

我的家庭作业遇到了一个问题,需要一些帮助。

//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();
~~~~~~~~~~~~~~~~~~~^~~~~~

非常感谢您的帮助!

阅读代码表明您正试图对std::string中的字符调用erase()。如果要擦除字符串中的字符,则需要调用std::string中的erase()函数。我建议使用迭代器在字符串中循环,因为在使用整数索引进行迭代的字符串上使用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 */
}