【问题标题】:C++ - MPIR: mpz_t to std::string?C++ - MPIR:mpz_t 到 std::string?
【发布时间】:2013-04-05 03:56:00
【问题描述】:

我们如何将 mpz_t 转换为 std::string?

mpz_t Var;

// Var = 5000
mpz_init_set_ui( Var, 5000 );

std::string Str = "";
// Convert Var to std::string?

mpz_clear( Var );

【问题讨论】:

标签: c++ gmp


【解决方案1】:

你正在寻找mpz_get_str:

char * tmp = mpz_get_str(NULL,10,Var);
std::string Str = tmp;

// In order to free the memory we need to get the right free function:
void (*freefunc)(void *, size_t);
mp_get_memory_functions (NULL, NULL, &freefunc);

// In order to use free one needs to give both the pointer and the block
// size. For tmp this is strlen(tmp) + 1, see [1].
freefunc(tmp, strlen(tmp) + 1);

但是,您不应该在 C++ 程序中使用 mpz_t。请改用mpz_class,因为它提供了get_str() 方法,该方法实际上返回std::string,而不是指向某些已分配内存的指针。

【讨论】:

  • mpz_get_str返回的内存不要使用free,需要用mp_get_memory_functions查询分配函数。
  • @MarcGlisse:我知道,但我想简化这个例子。此外,如果他没有更改内存功能,则默认释放器应该是free。除此之外,他应该简单地使用 C++ 类。
  • @MarcGlisse 我很想看看如何使用mp_get_memory_functions 来销毁mpz_get_str 返回的char * 的示例。你能提供一个吗?
  • gmpxx.h中有一个。
  • 我应该首先添加mp_get_memory_functions,这样可以为你们节省一些时间,抱歉。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-14
  • 2020-01-04
  • 2017-06-16
相关资源
最近更新 更多