1 1 5 7 5
6 3 0 4 0
6 9 0 4 0
8 4 3 3 1
8 2 8 8 0
7 8 6 4 4
7 6 4 4 0
9 4 2 4 0
void something(vector < vector <int> > v)
{
sort(v.begin(), v.end());
int uniqueCount = std::unique(v.begin(), v.end()) - v.begin();
count = uniqueCount-1;
}
我想计算除0以外的其他数字。在这种情况下,是1 3 4 5 = 4个唯一数字。我没有得到正确的答案,它正在尝试删除矩阵的几行。
答案 0 :(得分:5)
我建议使用std::set进行以下实现,该实现将每个值存储一次:
#include <set>
#include <vector>
#include <iostream>
using namespace std;
int count_object(vector<vector<int>> &matrix)
{
std::set<int> s;
for(auto &v : matrix)
s.insert(v.begin(), v.end());
s.erase(0);
return s.size();
}
int main()
{
vector<vector<int>> v = { { 1, 2, 3 }, { 3, 2, 1 }, { 0, 4, 1 } };
std::cout << "Unique numbers: " << count_object(v);
}
答案 1 :(得分:1)
如果由于某种原因您不能使用集合,只需在关于count_if的第一条评论上展开
// flatten the 1D Vector
vector<int> all_ints;
for(auto& currv : N)
{
all_ints.insert(all_ints.end(), currv.begin(), currv.end());
}
std::map<int,bool> unique_ints_map;
// use a lambda expression to count new elements
int unique_items = std::count_if(all_ints.begin(), all_ints.end(),
[&unique_ints_map](int i)
{
// Element exists already so shouldn't be added
if( unique_ints_map.count(i) > 0 )
{
return false;
}
// Throw out zeros too since you don't want to count it
if( i == 0)
{
return false;
}
// This is a new unique number, add it to our map so we don't count again
unique_ints_map[i] = true;
return true;
}
);
std::cout << "unique_items: " << unique_items << '\n';