[英]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.