2

在这里,我试图用 C++ 中的xtensor库做一个非常基本的操作。我有 xarray a,并且使用与索引相关的函数 xt::where,我想获取条件为 True 的索引数组(注意,还有另一个 xt::where 函数,但它是一个运算符函数,我不想要它)。当我尝试用这一行编译它时,我得到了很多错误:

g++ -I/usr/include/xtensor -I/usr/local/include/xtl getindx.cpp -o getindx

奇怪的是,当我尝试使用另一个 xt::where 函数(运算符函数)时,它可以工作、编译和运行。我显然错过了一些东西;我正在搜索,但我无法通过,请帮助我!谢谢你。

这是代码:

#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"
#include "xtensor/xview.hpp"
#include "xtensor/xoperation.hpp"
#include "xtensor/xtensor.hpp"


using namespace std;

int main(int argc, char** argv){

  xt::xarray<double> arr {5.0, 6.0, 7.0};
  auto idx = xt::where(arr >= 6);

  std::cout << idx << std::endl;

 return 0;

}

编辑:错误。

error: no match for ‘operator<<’ (operand types are ‘std::ostream {aka std::basic_ostream<char>}’ and ‘std::vector<std::vector<long unsigned int>, std::allocator<std::vector<long unsigned int> > >’)
   std::cout << idx << std::endl;

EDIT2:在没有 xtensor 的情况下解决。也许它会慢一些。



int main(int argc, char** argv){

 
  std::vector<double> arr{5.0,6.0,7.0};
  std::vector<unsigned int> indices;
  
  auto ptr = &bits[0];
  for (int i = 0; i<arr.size(); i++, ptr++)
    {
      if (*ptr>=6) indices.push_back (i);    
   }

  for (int i=0; i<indices.size(); i++){
    cout << "indices= "indices[i] << endl;
  } //output: indices=1, indices=2.
 return 0;
}
4

1 回答 1

0

问题是xt::where(或者xt::argwhere这里的语法更具描述性)返回一个std::vector或数组索引,其中没有operator<<重载,例如用于打印。

为了解决这个问题xt::from_indices而创建。从相关文档页面

int main()
{
    xt::xarray<size_t> a = xt::arange<size_t>(3 * 4);

    a.reshape({3,4});

    auto idx = xt::from_indices(xt::argwhere(a >= 6));

    std::cout << idx << std::endl;
}

在这种情况下idx,也可以键入xt::xarray<size_t>,或者xt::xtensor<size_t, 2>如果您想更详细地使用auto.

于 2020-10-19T08:16:19.370 回答