再次请教一个关于数组的方程!!

pitachiocrepe 2014-05-11 06:54:14
题目是
在一个数组中,如果有几个相同的元素连续排在一起,那么只保留一个,返回值是最后数组中的元素个数。
原题如下:
int removeDups(string a[], int n);
For every sequence of consecutive identical items in a, retain only one item of that sequence. Suppose we call the number of retained items r. Then when this functions returns, elements 0 through r-1 of a must contain the retained items (in the same relative order they were in originally), and the remaining elements may have whatever values you want. Return the number of retained items. Here's an example:
string d[9] = {
"lois", "chris", "peter", "peter", "meg", "meg", "meg", "peter", "peter"
};
int p = removeDups(d, 9); // returns 5
// d[0] through d[4] now contain "lois" "chris" "peter" "meg" "peter"
// We no longer care what strings are in d[5] and beyond.

我的程序是:
int removeDups(string a[], int n)
{
if (n<0)
return -1;
else
{
string item;
for (int i=0; i<n-1; i++)
{
item = a[i];
if (item == a[i+1])
{
for (int j=i+1; j<n; j++)
{
a[j-1]=a[j];
}
i--;
n--;
}
}
return n;
}
}
请大神指教哪里错了??
...全文
64 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
「已注销」 2014-05-11
  • 打赏
  • 举报
回复
// 代码没有错
#include <stdlib.h>
#include <stdio.h>
#include <string>
using namespace std;


int removeDups(string a[], int n)
{
    if (n<0)
        return -1;
    else
    {
        string item;
        for (int i=0; i<n-1; i++)
        {
            item = a[i];
            if (item == a[i+1])
            {
                for (int j=i+1; j<n; j++)
                {
                    a[j-1]=a[j];
                }
                i--;
                n--;
            }
        }
        return n;
    }
}

int main(){
	string d[9] = {"lois", "chris", "peter", "peter", "meg", "meg", "meg", "peter", "peter"};
	int p = removeDups(d, 9);  //  returns 5
	printf("%d",p);
	
	return 0;
}
/*
output:
9
  */
pitachiocrepe 2014-05-11
  • 打赏
  • 举报
回复
求助求助!!!!!1

65,208

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧