Search code examples
c++iteratorstdeigen3

How can I use stl iterators with Eigen?


I am trying to use the Library Eigen in a project and I have to sort a vector. I tried to follow the documentation and it says that the library should work in the predictable way with the STL iterators and algorithms https://eigen.tuxfamily.org/dox-devel/group__TutorialSTL.html. However when I try to run the following test code

#include <iostream>
#include <algorithm>
#include <eigen3/Eigen/Dense>
#include <eigen3/Eigen/Core>
int main()
{
    Eigen::Array4i v = Eigen::Array4i::Random().abs();
    std::cout << "Here is the initial vector v:\n" << v.transpose() << "\n";
    std::sort(v.begin(), v.end());
    std::cout << "Here is the sorted vector v:\n" << v.transpose() << "\n";
    return 0;
 }

I get the two following errors:

error: ‘Eigen::Array4i’ {aka ‘class Eigen::Array<int, 4, 1>’} has no member named ‘begin’
9 | std::sort(v.begin(), v.end());
  |             ^~~~~
error: ‘Eigen::Array4i’ {aka ‘class Eigen::Array<int, 4, 1>’} has no member named ‘end’
9 | std::sort(v.begin(), v.end());

I tested it with gcc 9.1.0 and 7.4.0 and my version of Eigen is 3.3.4. I am using Ubuntu 18.04 and the library is in the usual location /usr/include. All the other functionality I tried seem to work properly. Is it a well known bug, is it a compiler problem or is it a version problem?


Solution

  • If you don't want to wait for the release of Eigen 3.4, you can use this:

    std::sort(v.data(), v.data() + v.size());
    

    The .data() method can replace the missing .begin(), but the .end() method must be constructed manually.