在 C++ 中,我试图用函数指针编写一个函数。如果为不存在的函数传递函数指针,我希望能够抛出异常。我试图像处理普通指针一样处理函数指针并检查它是否为空
#include <cstddef>
#include <iostream>
using namespace std;
int add_1(const int& x) {
return x + 1;
}
int foo(const int& x, int (*funcPtr)(const int& x)) {
if (funcPtr != NULL) {
return funcPtr(x);
} else {
throw "not a valid function pointer";
}
}
int main(int argc, char** argv) {
try {
int x = 5;
cout << "add_1 result is " << add_1(x) << endl;
cout << "foo add_1 result is " << foo(x, add_1) << …Run Code Online (Sandbox Code Playgroud) 我在R中使用dplyr表.典型字段是主键,标识组的id号,日期字段和一些值.有些数字我做了一些操作,在一些初步步骤中抛出了大量数据.
为了进行我的分析的下一步(在MC Stan中),如果日期和组ID字段都是整数索引会更容易.所以基本上,我需要将它们重新索引为1之间的整数和不同元素的总数(对于group_id约为750,对于date_id约为250,group_id已经是整数,但日期不是).将它导出到数据框后,这是相对简单的做法,但我很好奇是否可以在dplyr中.
我尝试创建一个新的date_val(名为date_val_new)如下.根据评论中的讨论,我有一些假数据.我有目的地使组和日期值不是1,但我没有把日期作为实际日期.我使数据不平衡,删除一些值来说明问题.无论date_val是什么,dplyr命令都会为每个新组重新启动索引为1.因此即使日期不同,每组也从1开始.
df1 <- data.frame(id = 1:40,
group_id = (10 + rep(1:10, each = 4)),
date_val = (20 + rep(rep(1:4), 10)),
val = runif(40))
for (i in c(5, 17, 33))
{
df1 <- df1[!df1$id == i, ]
}
df_new <- df1 %>%
group_by(group_id) %>%
arrange(date_val) %>%
mutate(date_val_new=row_number(group_id)) %>%
ungroup()
Run Code Online (Sandbox Code Playgroud) 通过C++中的共享对象访问成员变量的安全方法是什么?
在下面的代码中,我创建一个共享变量,然后指向它的成员变量.但是,use_count保持不变,当我重置共享变量时,原始变量被重置但不是指向成员的指针.
换句话说,我可以通过使用b来介绍一些错误.它指向的对象不再存在.
#include <iostream>
#include <memory>
using namespace std;
struct A
{
int y;
A(int x)
{
y = x;
}
};
int main()
{
auto a = make_shared<A>(1);
cout << "a count: " << a.use_count() << endl; //prints a count: 1
auto b = a->y;
cout << "a count: " << a.use_count() << endl; //still prints a count: 1
a.reset();
cout << "a value: " << a << endl; //prints a value: 0
cout << "b value: " …Run Code Online (Sandbox Code Playgroud)