我混淆了如何实现左移函数来替换重复元素。我尽力对我的代码进行评论。请指出我的错误,这样我就可以自己改正了。
template <typename T>
void shift_left(T *a, int &a_size)
{
T*b ; // walker to check if the same element
b=a; //point b to a address
b++; //move b to the next element
int *endptr; //declare end pointer
endptr += a_size; // end pointer to the end
int *c; // c pointer to shift element back
int i =0, j;
while (i < a_size && b != endptr) //true when counter smaller than
//arr size and b point not at the end
{
if (*a != *b)
{
b++; //increment b if a !=b
}
else if (*a == *b) // a ==b
{
*b = *b++; // replace next element with b element
a_size--; //reduct arr size
}
}
for (j = 0; j < a_size; j++) // print out array loop
{
cout<< *a << "t";
a++;
}
}
请指出我的错误,这样我就可以自己纠正了。
您忽略了编译器的警告。
问题是,您单独发布的代码不会触发许多警告或错误(gcc只抱怨cout
(。您必须通过实例化模板来帮助编译器:
int main() {
auto f = shift_left<int>;
}
有了gcc,我通过-Wall
打开了更多的警告(它不是真正的"所有",而是"所有常见的"(,我希望通过-Werror
将警告作为eror,并获得以下输出:
<source>: In function 'int main()':
<source>:32:10: error: unused variable 'f' [-Werror=unused-variable]
32 | auto f = shift_left<int>;
| ^
<source>: In instantiation of 'void shift_left(T*, int&) [with T = int]':
<source>:32:14: required from here
<source>:20:13: error: operation on 'b' may be undefined [-Werror=sequence-point]
20 | *b = *b++; // replace next element with b element
| ^
<source>:20:13: error: operation on 'b' may be undefined [-Werror=sequence-point]
<source>:9:10: error: unused variable 'c' [-Werror=unused-variable]
9 | int *c; // c pointer to shift element back
| ^
<source>: In function 'void shift_left(T*, int&) [with T = int]':
<source>:8:12: error: 'endptr' is used uninitialized in this function [-Werror=uninitialized]
8 | endptr += a_size; // end pointer to the end
| ~~~~~~~^~~~~~~~~
第一个只是main
中未命名的f
,我们现在可以忽略它。那么*b = *b++
很可能是错误的。CCD_ 7看起来未被使用,而CCD_。
上面的main
只是实例化了模板。作为下一步,您需要实际调用函数来测试它。您需要使用您知道预期输出的输入,以便进行比较。如果它们匹配,你可能测试得不够,如果不匹配,你想使用调试器来查找代码中的错误。