也許最好使用一些關聯容器,例如std::unordered_map
或std::multimap
。
下面是一個示範程序
#include <iostream>
#include <map>
int main()
{
int grid[] =
{
1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2,
4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6,
4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8,
4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8
};
std::multimap<int, int> m;
int i = 0;
for (int x : grid)
{
m.insert({ x, i++ });
}
std::multimap<int, int>::size_type n = m.count(1);
std::cout << "There are " << n << " elements of color 1:";
auto p = m.equal_range(1);
for (; p.first != p.second ; ++p.first)
{
std::cout << ' ' << p.first->second;
}
std::cout << std::endl;
return 0;
}
輸出
There are 6 elements of color 1: 0 1 8 9 10 17
或者
#include <iostream>
#include <map>
int main()
{
int grid[] =
{
1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 3, 3, 3, 2, 2,
4, 1, 5, 3, 3, 6, 2, 6, 4, 5, 5, 5, 3, 6, 2, 6,
4, 4, 5, 5, 5, 6, 6, 6, 4, 7, 7, 8, 5, 8, 8, 8,
4, 7, 7, 8, 8, 8, 8, 8, 4, 7, 7, 7, 7, 8, 8, 8
};
std::multimap<int, int> m;
int i = 0;
for (int x : grid)
{
m.insert({ x, i++ });
}
for (auto first = m.begin(); first != m.end();)
{
auto n = m.count(first->first);
std::cout << "There are " << n
<< " elements of color " << first->first << ":";
auto p = m.equal_range(first->first);
for (; p.first != p.second ; ++p.first)
{
std::cout << ' ' << p.first->second;
}
std::cout << std::endl;
first = p.first;
}
return 0;
}
輸出是
There are 6 elements of color 1: 0 1 8 9 10 17
There are 10 elements of color 2: 2 3 4 5 6 7 14 15 22 30
There are 6 elements of color 3: 11 12 13 19 20 28
There are 7 elements of color 4: 16 24 32 33 40 48 56
There are 8 elements of color 5: 18 25 26 27 34 35 36 44
There are 7 elements of color 6: 21 23 29 31 37 38 39
There are 8 elements of color 7: 41 42 49 50 57 58 59 60
There are 12 elements of color 8: 43 45 46 47 51 52 53 54 55 61 62 63
使用'std :: vector'。 – 101010 2014-09-02 20:57:17
'int target_number = max_number - max_number + 1'可以簡化爲'int target_number = 1',但也許這是一個錯字 – CarCzar 2014-09-02 20:59:10
@ 40two我是新手,矢量不超出我的技能範圍? – mrmike 2014-09-02 21:00:20