为什么断言在这里不起作用
Why does assert not work here?
这是代码:
#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政策页面:
包装中提供的代码和示例永远不要做任何事情 可能被视为恶意或反社会。以下是 过去经验的说明性示例。
- 编译的代码绝不应终止其运行的R过程。因此,C/C 调用
assert
/abort
/exit
,fortran调用 必须避免使用STOP
等。R代码也可以致电q()
。
因此,关于调试模式的答案在技术上是正确的,但也请注意,如果您打算在某个时候上传cran,则不应使用此功能。
通过使用throw
而不是assert
解决了问题,RCPP实际上将把东西放在适当的try-catch块中,这非常好。
#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();
Rcout << nx << 'n' << ny << std::endl;
if(nx != ny) {
throw std::invalid_argument("Two vectors are not of the same length!");
}
double dist=0;
for(int i = 0; i < nx; i++) {
dist += pow(x[i] - y[i], 2);
}
return sqrt(dist);
}
用于G 使用-g启用调试选项:
g++ -g code.cpp
或视觉工作室中的调试模式。
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 为什么在保护模式下继承升级不起作用
- 循环在计数器中不起作用
- 在其他文件中创建类时在 c++ 项目中不起作用
- 为什么二进制搜索在我的测试中不起作用
- 为什么 const std::p air<K,V>& 在 std::map 上基于范围的 for 循环不起作用?
- 带有指定长度字符* 参数的 std::regex_search 在 VS2017 中不起作用?
- 为什么简单的算术减法在"if"条件下不起作用?
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 通过 get-Method 访问变量在类外不起作用
- 为什么 ulimit -v 在 Clang 的地址清理器下不起作用?
- G++ C++17 类模板参数推导在非常特殊的情况下不起作用
- 我的C++合并排序代码不起作用。我在这里错过了什么?
- C++ 互斥锁可以交叉方法/变量吗?如果是这样,为什么在这里不起作用?
- 不明白为什么动态编程在这里不起作用
- 为什么断言在这里不起作用
- 为什么 [] 的重载函数在这里不起作用?
- 为什么glDrawPixel在这里不起作用
- 在 qt 中添加 += -std=c++11 QMAKE_CXXFLAGS 到 .pro 文件中不起作用(在 Linux
- 每当启动函数 game() 时,get(c) 第一次在循环中不起作用(在第 90 行中)。