![](/img/trans.png)
[英]C++ Filling an 1D array to represent a n-dimensional object based on a straight line segment
[英]Filling an 1D array in C++
我有一个 integer 数组:
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
我想要做的是根据多重性创建另一个数组。 所以我定义了另一个数组:
int multi[7]={0};
多数组 multi[0] 的第一个索引将告诉我们数组 listint 的重数为零。 我们可以很容易地看到,数组 listint 中没有零,因此第一个成员是 0。第二个是 1 个香料,数组中只有 1 个成员。 类似地,multi[2] position 是 listint 中 2 的重数,即 3,因为 listint 中有 3 个 2。
我想用一个 for 循环来做这件事。
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
multi[j] = 1;
}
cout << "multi hit \n" << multi[1] << endl;
return 0;
}
运行这段代码后,我想我会想要 listint 数组的每个元素的多重性。 所以我尝试使用二维数组。
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int i, j;
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[7][10] = { 0 };
for (int i = 0; i < 9; i++)
{
if (i == listint[i])
count++;
j = count;
for (j = 0; j < count; j++) {
multi[j][i] = 1;
}
}
cout << "multi hit \n" << multi[4][i] << endl;
return 0;
}
第一个代码块是我想打印出多重性的东西。 但后来我发现,我想在一个数组中表示每个元素的多重性。 那么二维数组不是个好主意吗? 我没有成功使用二维数组运行代码。
另一个问题。 当我分配 j = count 时,我的意思是这就是多重性。 所以如果count的值为2; 我认为这是数组listint中任何元素的两个多重性。
如果您只是想获取列表中每个元素的计数,则不需要二维数组。
#include <iostream>
int main() {
int listint[10] = { 1,2,2,2,4,4,5,5,7,7, };
int multi[8] = { 0 };
for (int i : listint)
++multi[i];
for (int i = 0; i < 8; ++i)
std::cout << i << ": " << multi[i] << '\n';
return 0;
}
使用标准集合std::map
还有一种更简单更好的方法。 值得注意的是,这不需要您事先知道数组中最大的元素是什么:
#include <map>
#include <iostream>
int main() {
int listint[10] = {1,2,2,2,4,4,5,5,7,7,};
std::map<int, int> multi;
for (int i : listint)
multi[i]++;
for (auto [k,v] : multi)
std::cout << k << ": " << v << '\n';
}
试试这个,因为你是初学者,所以地图对你不起作用,很简单:
#include <iostream>
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count;
int j;
int listint[10] = {1,2,2,2,4,4,5,5,7,7};
int multi[8]={0};
for(int i=0; i<10; i++)
{
multi[listint[i]]++; // using listint arrays elements as index of multi to increase count.
}
for( int i=1; i<8; i++)
{
cout << "multi hit of "<<i<<" : "<< multi[i]<<endl;
}
return 0;
}
或者如果数字可能变大并且未知但已排序
#include <iostream>:
#include <stdio.h>
using namespace std;
int main()
{
unsigned int count = 0;
int index = 0; // used to fill elements in below arrays
int Numbers[10] = {0}; // storing unique numbers like 1,2,4,5,7...
int Count[10] = {0}; // storing their counts like 1,3,2,2,2...
int listint[10] = {1, 2, 2, 2, 4, 4, 5, 5, 7, 7};
for(int i = 0; i < sizeof(listint) / sizeof(listint[0]); i++)
{
count++;
if (listint[i] != listint[i+1]) {
Numbers[index] = listint[i];
Count[index] = count;
count=0;
index++;
}
}
for(int i=0; i<index; i++)
{
cout << "multi hit of "<<Numbers[i]<<" is " << Count[i]<<endl;
}
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.