Tom de Geus Tom de Geus - 1 year ago 74
C++ Question

Find difference between two lists using Eigen

I would like to find the difference between two lists. For example:

// two lists:
A = [ 0, 1, 2, 3, 4, 5, 6 ];
B = [ 1, 4, 5 ];

// difference between the lists:
C = [ 0, 2, 3, 6 ];


I have done this using the STL-library of C++ as follows:

#include <iostream>
#include <vector>

int main()
{
std::vector<size_t> A = {0, 1, 2, 3, 4, 5, 6};
std::vector<size_t> B = {1, 4, 5};
std::vector<size_t> C;

std::set_difference(A.begin(),A.end(), B.begin(),B.end(), std::inserter(C,C.begin()));

return 0;
}


However, because my application uses mostly Eigen, I now would like to do also this using Eigen. I couldn't find what I was looking for in the documentation nor online.

Note that I specifically want to avoid writing my own function.

Answer Source

Here you go:

#include <iostream>
#include <Eigen/Dense>

int main()
{
    using namespace Eigen;

    VectorXd a(3), b(1), c(2);
    a << 1,2,3;
    b << 1;

    std::set_difference(a.data(), a.data() + a.size(), 
                        b.data(), b.data() + b.size(), 
                        c.data());

    std::cout << c;
}

The key here is to use Eigen::VectorXd::data() member function, which returns a pointer to the underlying storage, which is itself an iterator that can be passed around to C++ standard library functions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download