Search code examples
c++eigen

How do I compare two dynamic arrays and check which elements match?


I want to compare two matrices element-wise and return a matrix containing a 1 if the elements in that location match, or a 0 otherwise. I created a simple test function that does this:

template <class A, class B>
void func(const A& a, const B& b)
{
    auto c = (b.array() == a.array()).cast<int>();
    std::cout << c;
}

So I wrote a main function like this to test it:

int main()
{
    Eigen::Array<int,Eigen::Dynamic,Eigen::Dynamic> b;

    b.resize(2,2);
    b.fill(2);

    auto a = b;
    a(0,0) = 1;
    a(0,1) = 2;
    a(1,0) = 3;
    a(1,1) = 4;

    func(a,b);
    return 0;
}

But I keep getting this error:
eigenOperations.cpp: In function ‘void func(const A&, const B&)’: eigenOperations.cpp:8:24: error: expected primary-expression before ‘int’ auto c = temp.cast<int>(); eigenOperations.cpp:8:24: error: expected ‘,’ or ‘;’ before ‘int’ make: *** [eigenOperations] Error 1

What am I doing wrong here?


Solution

  • Whoever marked this as duplicate was right. The problem does arise because I didn't fully understand the C++ template keyword.

    Where and why do I have to put the "template" and "typename" keywords?

    Replacing the function with the following fixed the problem:

    template <class A, class B>
    void func(const A& a, const B& b)
    {
        auto c = (b.array() == a.array()).template cast<int>();
        std::cout << c;
    }