定义map<int,vector<int>>返回类型会在每次运行时给出随机值

2024-04-26 21:40:33 发布

您现在位置:Python中文网/ 问答频道 /正文

在使用python main.py构建并调用它之后,它会给出如下结果:

[array([22209328, 21870, 0], dtype=int32), array([24088960, 21870, 1], dtype=int32)]

为什么会这样?我找不到代码中的错误。 我只得到每个数组的最后一个元素是正确的。其余部分显示一些随机数,我假设是地址。你知道吗

预期输出:

[array([1, 0, 0], dtype=int32), array([2, 1, 1], dtype=int32)]

小时_地图.cpp

#include <stdio.h>
#include <math.h>
#include <map>
#include <vector>
#include <iostream>

using namespace std;
map<int, vector<int> >hash_map()
{
    map<int, vector<int> >dist;
    for(int i=0;i<2;i++)
    {
        dist[i] = {i+1,i,i}; // 1,0,0    2,1,1
        // 0 --> 1,2,3,
        // 1-> 2,3,4
    }
    return dist;
}

h\u地图.h

#ifndef H_MAP_H
#define H_MAP_H
#include <vector>
#include <map>
using namespace std;
map<int, vector<int> >hash_map();

#endif

hïu map.i

%module h_map
#define SWIGPYTHON_BUILTIN
%{
  #include "numpy/arrayobject.h"
  #define SWIG_FILE_WITH_INIT  /* To import_array() below */
  #include "h_map.h"
%}
%include "std_map.i"
%import "std_vector.i" 
%include "numpy.i"

%init %{
    import_array();
%}

namespace std {
    %template(IntVector) vector<int>;
}
namespace std {
 %template (mapiv) std::map<int,vector<int> >;
}

%typemap(out) std::map<int, std::vector<int> >
{
    for(auto it:$1)
    {
        int subLength = it.second.size();
        npy_intp dims[1] = {subLength };
        PyObject* temp = PyArray_SimpleNewFromData(1, dims, PyArray_INT, it.second.data());
        $result = SWIG_Python_AppendOutput($result, temp);        
    }       
}
%include "h_map.h"```

生成.sh

g++ -fPIC -c h_map.cpp

swig -python -c++ -o h_map_wrap.cpp h_map.i

g++ -fPIC -c $(pkg-config --cflags --libs python3) -I /home/kriti/anaconda3/lib/python3.7/site-packages/numpy/core/include  h_map_wrap.cpp

g++ -shared h_map.o h_map_wrap.o -o _h_map.so -lm

主.py

import numpy as np
from h_map import hash_map
a = hash_map()
print(a)

更新:

map<int, vector<int> >dist;
for(int i=0;i<2;i++)
{
    for (int j =0;j<3;j++)
        dist[i].push_back(i*j);
}

这样做之后,问题还是一样的。你知道吗


Tags: importnumpymapforincludedisthashnamespace