c++ - 使用指针从 C++ 中的排序数组中删除重复项时出错
问题描述
我的任务是从排序数组中删除重复项。
但是,当我尝试这样做时,它不会删除任何内容,并且仍然在输出中为我提供与原始值相同的值。
我想我在removeDuplicates()
函数中遗漏了一些东西。
还建议使用指针表示法。谢谢!
void removeDuplicates(int *arr, int *size)
{
int s,*p,i,k=0;
p=arr;
s=*size;
int arr1[s];
for(i=0;i<s-1;i++)
{
if (*(p+i)!=*(p+i+1))
{
arr1[k++]=*(p+i);
}
}
arr1[k++]=*(p+s-1);
for(i=0; i<k; i++)
{
*(p+i) = arr1[i];
}
for(i=0; i<k; i++)
{
cout<<*(p+i)<<endl;
}
}
解决方案
对于初学者,可变长度数组作为函数中声明的数组
int arr1[s] = {};
不是标准的 C++ 功能。此外,在存在可变长度数组的 C 语言中,您可能不会在它们的声明中初始化它们。
此外,如果源数组仅包含一个或两个不同的元素,则变量的值k
将不正确,等于0
(而不是1
)或 1(而不是2
)。
除此之外,该函数不应输出任何内容。它是函数的调用者决定是否输出唯一元素的子数组。由于第二个参数在 C 语言中是通过引用传递的,因此它应该在函数内进行更改。
有std::unique
可用于完成任务的标准算法。这是一个演示程序。
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
int a[] = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };
auto last = std::unique( std::begin( a ), std::end( a ) );
for ( auto first = std::begin( a ); first != last; ++ first )
{
std::cout << *first << ' ';
}
std::cout << '\n';
return 0;
}
程序输出为
1 2 3 4 5
如果您想自己使用函数中的指针为数组编写类似的函数,那么它可以通过以下方式查找
#include <iostream>
template <typename T>
size_t removeDuplicates( T *a, size_t n )
{
T *dest = a;
if ( n != 0 )
{
++dest;
for ( T *current = a; ++current != a + n; )
{
if ( *current != *( dest - 1 ) )
{
if ( dest != current )
{
*dest = *current;
}
++dest;
}
}
}
return dest - a;
}
int main()
{
int a[] = { 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5 };
const size_t N = sizeof( a ) / sizeof( *a );
size_t last = removeDuplicates( a, N );
for ( size_t first = 0; first != last; ++first )
{
std::cout << a[first] << ' ';
}
std::cout << '\n';
return 0;
}
程序输出再次是
1 2 3 4 5
推荐阅读
- vuepress - Vuepress 中的自定义标题内容
- angular - 为什么值出现在垫子扩展面板之外?
- python-3.x - 我正在构建一个计数器,如何在 for 循环中更新字典列表(python)
- c# - 为什么 Visual Studio 能够从 DLL 中获取方法名称而 dumpbin 不能
- android - Android 理解意图
- mysql - 未在 Symfony 4 中使用原始查询的奴隶
- reactjs - React路由器,如何将路由重定向到其子路由?
- json - 我可以根据输入中的嵌套属性输出带有 jq 的属性吗?
- sql - 在我的 SQL where 子句中需要动态日期
- mysql - 连接 2 个表时 1 列中有多个值