如何在阵列末尾发送重复元素? [英] How do I send duplicated elements at the end of the array?

查看:58
本文介绍了如何在阵列末尾发送重复元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须找到给定数组中的所有重复元素,并在最后以原始顺序发送它们。

例如:

输入:2 3 2 4 5 4 3 7 1 2 6

输出:2 3 4 5 7 1 6 2 4 3 2

在我的问题中,大小已经确定(11)但不管怎样都不是问题。



我解决了这个问题但是我收到这样的错误:



运行时检查失败#2 - 变量'a'附近的堆栈已损坏。



我想这是因为我尝试使用数组的边界。

我的问题是我应该做些什么改变才能留在边界和也有正确的输出?



我尝试过:



I have to find all duplicate elements in a given array and send them at the end with their original order.
For example:
Input: 2 3 2 4 5 4 3 7 1 2 6
Output: 2 3 4 5 7 1 6 2 4 3 2
In my question size is already determined(11) but it is not a problem anyway.

I solve the problem but I get an error like this:

"Run-Time Check Failure #2 - Stack around the variable 'a' was corrupted."

I suppose it happens because I try to use out of the borders of the array.
My question is what changes I should do in order to stay in the borders and also have the right output?

What I have tried:

MY Code is:

#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;
#define SZ 11
int main()
{
	
	ifstream fs("C:\\Users\\Can\\Desktop\\file.txt");
	if (!fs)
		return 0;
	int a[SZ];
	for (int i = 0; i < SZ; ++i)
		fs >> a[i];
	
	int b, c, d;

	for (b = 0; b < SZ; b++)
	{
		for (c = b + 1; c < SZ; c++)
		{
			if (a[b] == a[c])
			{
				for (d = c; d < SZ; d++) {
					int temp = a[b];
					a[d] = a[d + 1];
					a[SZ-1] = temp;
				}
			}
		}
	}

	for (int i = 0; i < SZ; ++i)
		cout << a[i] << " ";

	return 1;
}

With this code I get output: 2 3 4 5 7 1 2 3 4 2 2

If I change "a[SZ -1] = temp" to "a[SZ] = temp" I get the right output but also an error.

Please help me find the mistakes in my code.
Also forget about the file, just think it as a given input above.

推荐答案

首先要注意的是你不想就地这样做 - 你真的需要一个单独的输出数组来加载你的数据。如果你试图在同一个数组中这样做,你会遇到一些问题。

所以创建第二个数组,然后运行输入。

开始通过运行三个索引或指针:In,Out,Temp:稍后在与In相同的地方开始。

然后循环:

如果In中的值不在输出,复制到那里,然后输出

如果是,请将其复制到Temp,并将其复制到Temp。

Inc In。

完成之后,将你复制的所有值复制到Temp to Out。



如果这没有意义,请用铅笔和纸试试 - 它应该制作一旦你看到发生了什么,就会很快意识到。
The first thing to note is that you don't want to do this "in place" - you really need a separate output array to load your data into. If you try to do this in the same array, you are going to get problems with some cases.
So create a second array, and run through the input.
Start by running three indexes or pointers: In, Out, Temp: the later start at the same place as In.
Then loop:
If the value at In is not in Output, copy it there, and inc Out
If it is, copy it to Temp, and inc Temp.
Inc In.
When that's finished, copy all the values you copied to Temp to Out.

If that doesn't make sense immediately, try it with a pencil and paper - it should make sense very quickly once you see what's happening.


这篇关于如何在阵列末尾发送重复元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆