2

我将 C++ 与犰狳库一起使用。当我打印一个向量或矩阵时,在向量/矩阵之后总是包含一个换行符,即使使用 .raw_print() 也是如此。有什么简单的方法可以禁用这种行为吗?

最小的例子:

#include <iostream>
#include <armadillo>

using namespace std;
using namespace arma;

int main() {
    rowvec a;
    a << 0 << 1 << 2;
    cout << a;
    a.print();
    a.raw_print();

    mat b;
    b << 0 << 1 << 2 << endr
      << 3 << 4 << 5 << endr
      << 6 << 7 << 8;
    cout << b;
    b.print();
    b.raw_print();
}

我正在使用 GCC 版本 4.4.6 在 linux 上编译和运行

g++ test.cpp -o test -larmadillo
4

1 回答 1

3

Armadillo中的.print()函数旨在进行“漂亮打印”。.raw_print() 函数减少了漂亮打印的数量(即,它不会将数字的表示更改为科学格式),但仍会打印换行符。

如果这些函数的功能更少,那么它们不会比简单地循环遍历元素并将它们转储到用户流(例如cout )提供任何附加值。因此,解决方案就是自己进行打印,通过以下功能:

inline
void
my_print(const mat& X)
  {
  for(uword i=0; i < X.n_elem ++i) { cout << X(i) << ' '; }
  }

如果您希望在每行末尾有换行符(最后一行除外)的情况下进行最少量的漂亮打印,请尝试以下操作:

inline
void
my_print(const mat& X)
  {
  for(uword row=0; row < X.n_rows; ++row)
    {
    for(uword col=0; col < X.n_cols; ++col) { cout << X(row,col) << ' '; }

    // determine when to print newlines
    if( row != (X.n_rows-1) ) { cout << '\n'; }
    }
  }

请注意,上面的代码仅打印mat类型(这是Mat < double > 的 typedef)和派生类型,例如vecrowvec。如果要打印任何模板化的 Mat < T > 类型(以及派生类型 Col < T > 和 Row < T >),请尝试以下操作:

template<typename eT>
inline
void
my_print(const Mat<eT>& X)
  {
  for(uword row=0; row < X.n_rows; ++row)
    {
    for(uword col=0; col < X.n_cols; ++col) { cout << X(row,col) << ' '; }

    // determine when to print newlines
    if( row != (X.n_rows-1) ) { cout << '\n'; }
    }
  }

此外,如果您希望能够打印任何犰狳矩阵表达式(例如 A+B),请尝试以下操作:

template<typename T1>
inline
void
my_print(const Base<typename T1::elem_type,T1>& expr)
  {
  const Mat<typename T1::elem_type> X(expr);  // forcefully evaluate expression

  for(uword row=0; row < X.n_rows; ++row)
    {
    for(uword col=0; col < X.n_cols; ++col) { cout << X(row,col) << ' '; }

    // determine when to print newlines
    if( row != (X.n_rows-1) ) { cout << '\n'; }
    }
  }

请注意,如果表达式只是单个矩阵,则上面的代码将复制一个矩阵。如果需要效率,则需要模板元编程来避免复制,这超出了原始问题的范围。

于 2013-02-01T00:43:50.120 回答