gpt4 book ai didi

c++ - 为什么断言在这里不起作用?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:27:34 24 4
gpt4 key购买 nike

代码如下:

#include <Rcpp.h>
#include <iostream>
#include <assert.h>
#include <stdio.h>

using namespace Rcpp;


// [[Rcpp::export]]
double eudist(NumericVector x, NumericVector y) {
int nx = x.size();
int ny = y.size();
std::cout << nx << '\n' << ny << std::endl;
assert(nx == ny);

double dist=0;
for(int i = 0; i < nx; i++) {
dist += pow(x[i] - y[i], 2);
}

return sqrt(dist);
}

将其采购到 R 后,我得到以下结果,显然它在出现错误时不会中止:

#////////////////////////////////////////////////////
sourceCpp('x.cpp')
#////////////////////////////////////////////////////
eudist(c(0, 0), c(1, 1))
2
2
[1] 1.4142
#////////////////////////////////////////////////////
eudist(c(0, 0), c(1, 1, 1))
2
3
[1] 1.4142

最佳答案

请注意,assert() 等被明确禁止用于 CRAN 上传。引用自 CRAN Repo Policy页:

The code and examples provided in a package should never do anything which might be regarded as malicious or anti-social. The following are illustrative examples from past experience.

  • Compiled code should never terminate the R process within which it is running. Thus C/C++ calls to assert/abort/exit, Fortran calls to STOP and so on must be avoided. Nor may R code call q().

所以关于 Debug模式的答案在技术上是正确的,但也请注意,如果您计划在某个时候上传 CRAN,则不应该使用它。

关于c++ - 为什么断言在这里不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21409237/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com