C ++在数组中计算不同的元素

时间:2016-01-04 00:41:34

标签: c++ arrays

我需要找出2 D数组中有多少不同的元素。我的想法是通过2个for循环逐个遍历数组元素,然后检查旁边的元素是否不同。如果它的真实,则此元素将被移动或复制到新数组,并且原始数组将替换为(int0。只有当我从其他元素中添加不同的元素时,新数组中的元素数量才会增加。这是我的想法,如果有人更好(更容易),我会很高兴。 我目前的问题来自std::vector,我无法转换为bool。或者有更好的方法吗?

#include <stdio.h>
#include <vector>
#include <algorithm>
#include <iterator>

int numberofDifferent(int *array[], int lines, int columns)
{
    int result = 0;
    for (int i = 0; i < lines; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            if (array[i][j] != array[i][j+1])
            {
                std::vector<int>n;
                n.push_back(array[i][j]);
                if (bool exist = std::find(std::begin(n), std::end(n), array[i][j]))
                {
                    array[i][j] = 0;
                }
                else
                {
                    result++;
                }
            }
            else
            {
                break;
            }
        }
    }
    return result;
}

int main()
{
    int a[4][5] = { { 1, 2, 1, 2, 1 },
    { 2, 1, 3, 1, 2 },
    { 1, 2, 3, 2, 1 },
    { 3, 2, 1, 2, 3 } };
    int *array[4] = { a[0], a[1], a[2], a[3] };
    printf("number of different elements in array is: %d\n", numberofDifferent(array, 4, 5));  //correct answer: 3
}

//对不起我的语言

1 个答案:

答案 0 :(得分:1)

std::find返回找到的元素的迭代器,而不是bool。如果没有找到任何内容,它会将迭代器返回到搜索范围的末尾。所以,你需要进行比较:

if(std::find(std::begin(n), std::end(n), array[i][j]) != n.end())
    ...

删除了不必要的bool exists =部分。

这只是你的代码编译,但算法应该是不同的(为了效率,我没有检查有效性。)

修改

std::set可以为您整理重复项,然后您只需打印它的大小:

#include <iostream>
#include <set>

int main()
{
    int a[4][5] =
    {
        { 1, 2, 1, 2, 1 },
        { 2, 1, 3, 1, 2 },
        { 1, 2, 3, 2, 1 },
        { 3, 2, 1, 2, 3 }
    };

    std::set<int> set {&a[0][0], &a[3][4]};
    std::cout << "number of unique elements is: " << set.size() << std::endl;
}

Live on Coliru