C++ 用指针实现delete repeat函数
我不知道如何实现左移功能来替换重复元素。 我尽量对我的代码发表最好的评论。 请指出我的错误,这样我可以自己解决C++ 用指针实现delete repeat函数,c++,C++,我不知道如何实现左移功能来替换重复元素。 我尽量对我的代码发表最好的评论。 请指出我的错误,这样我可以自己解决 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
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++;
}
}
模板
无效左移(T*a、int和a\U大小)
{
T*b;//检查同一元素
b=a;//指向地址的b点
b++;//将b移动到下一个元素
int*endptr;//声明结束指针
endptr+=a_size;//指向末尾的结束指针
int*c;//c指向向后移位元素的指针
int i=0,j;
while(i
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>;
}
第一个是在main
中未启用的f
,我们现在可以忽略它。然后*b=*b++
很可能是错误的。c
似乎未使用,endptr
未初始化使用
上面的main
只是实例化了模板。下一步,您需要实际调用函数来测试它。您需要使用输入,您知道预期的输出,以便进行比较。如果它们匹配,您可能没有进行足够的测试,如果它们不匹配,您需要使用调试器来查找代码中的错误。(按问题)一个出局的人在这里,你给函数一些输入,并向我们展示你得到的输出以及你期望的输出。*b=*b++;
不做你认为它做的事情。而且,endptr
没有初始化。你应该初始化它,使它指向a
。它也不应该是int*
而是t*
。