c++检查数组中的重复项并替换它们
C++ check array for duplicates and replace them
我有一个充满值的数组,该数组不能包含任何重复的值。对于任何重复的值,将值加1。这里是代码我有到目前为止,但我仍然得到重复。(randArray是值所在的位置)。
for (int i = 0; i < sizeof(randArray) - 1; i++) {
for (int j = sizeof(randArray); j == 0; j--) {
if (randArray[i] == randArray[j]) {
randArray[i] == randArray[i] + 1;
}
}
}
您在增加副本时出现了打字错误:
randArray[i] = randArray[i] + 1; // not ==
同样,增量可能会创建另一个副本。如果是后面的项目,没有问题。但是由于数组没有排序,您可能无法捕获已经传递的值的新副本。
因此您可能需要多次传递:
bool wasaninc;
do {
wasaninc=false;
for ...
for ...
... // if there is an increment, set wasaninc to true
} while (wasaninc);
Change randArray[i] == randArray[i] + 1; to randArray[i] = randArray[i] + 1;
for (int i = 0; i < sizeof(randArray) - 1; i++) {
for (int j = sizeof(randArray); j == 0; j--) {
if (randArray[i] == randArray[j]) {
randArray[i] = randArray[i] + 1;
}
}
}
您的问题是由于sizeof(randArray)
。这个方法不返回数组中元素的个数。
int array[5] = { 1, 2, 3, 4, 5};
sizeof(array); // -> returns 20, because of 5 * 4 bytes (integer = 4 bytes)
不应该使用这个方法,而应该使用数组中元素的个数。您已经在开始时声明了数组的大小。因此,数组中可以有多少个元素就很清楚了。
正确的例子:
int array[100] = {...};
for (int i = 0; i < 99; i++) {
for (int j = 0; j < 99; j++) {
if (array[i] == array[j]) {
// code for duplicates
}
}
}
#include <iostream>
#include <unistd.h>
#include <algorithm>
using namespace std;
int main()
{
int arr[8]={0,1,1};
int n = sizeof(arr) / sizeof(arr[0]);
cout<<n<<"n";
/*Here we take two parameters, the beginning of the
array and the length n upto which we want the array to
be sorted*/
//sort(arr, arr + n);
for (int i=0;i<=n;i++){
cout<<arr[i]<<" ";
}
int result=0;
do{
for (int i=0;i<=n;i++){
for (int j =0;j<i;j++){
if(arr[j]==arr[i]){
srand(time(NULL)); // Seed the time
int finalNum = rand()%((10-1)+1); // Generate the number, assign to variable.
arr[i] = finalNum;
result = result + 1;
sleep(1);
i--;
}
}
}
}
while(result<=2);
n = sizeof(arr) / sizeof(arr[0]);
/*Here we take two parameters, the beginning of the
array and the length n upto which we want the array to
be sorted*/
//sort(arr, arr + n);
cout<<"n";
for (int i=0;i<=n;i++){
cout<<arr[i]<<" ";
}
return 0;
}
(我假设randArray
是一个c风格的数组) sizeof(randArray)
不返回数组中元素的数量,它返回randArray
占用的字节数。
示例(在wandbox上):
int main()
{
int arr[] = {1, 2, 3, 4};
// Prints 16! (on my machine)
std::cout << sizeof(arr) << "n";
}
在现代c++中使用数组的正确方法是使用std::array
或std::vector
。它们都提供了一个.size()
方法,返回集合中元素的个数。
你的代码失败的原因如下:
sizeof
不返回数组中元素的个数重复元素加1不能保证它是唯一的。
相关文章:
- valgrind-hellgrind与泄漏检查的结果不同
- C++模板来检查友元函数的存在
- 模板参数替换失败,并且未完成隐式转换
- 检查输入是否不是整数或数字
- 试图让变量检查数组中的某些内容
- 如何用转义符替换字符串中的所有特殊字符
- 检查值是否在集合p1和p2中,但不在p3中
- C++概念:如何使用'concept'检查模板化结构的属性?
- 概念TS检查忽略私有访问修饰符
- 检查 std::shared_ptr<> 的当前底层类型是否为 T
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- 如何在C++中检查2D数组中负值的输入验证
- C++:正在检查LinkedList中的回文-递归方法-错误
- 使用for循环检查数组中的重复项
- 如何检查一个c++字符串中有多少相同的字符/数字
- 替换枚举以最大化编译时间检查的最佳方法
- 如何检查和替换数组 C++ 中的元素
- 用可以检查边界 c++ 的东西替换数组的最接近的解决方案
- c++检查数组中的重复项并替换它们
- 我如何用在这个回调中具有编译时类型检查的东西替换void指针?