在 C/C++ 中是否有与 GNU-R 等效的函数,它()

Is there an equivalent function in C/C++ to GNU-R which()?

本文关键字:函数 GNU-R C++ 是否      更新时间:2023-10-16

让我解释一下'which'函数的作用:

来自 GNU-R 帮助:

哪些指数是正确的?

给出逻辑对象的"TRUE"索引,允许数组索引。

或显示一些代码:(GNU-R 从 1 开始计算索引)

> x <- c(1,2,3,1,3,5);
> which(x == 1);
[1] 1 4
> which(x == 3);
[1] 3 5
> ll <- c(TRUE,FALSE,TRUE,NA,FALSE,FALSE,TRUE);
> which(ll);
[1] 1 3 7

有谁知道 C/C++ 中的类似功能?

感谢您的帮助

林尼

你必须

明白R是矢量化的,而C首先是处理单个原子数据片段:单个intdouble,...

通过C++,您可以研究用于解决此问题的 STL 算法。

最后,在R和C++交叉点,我们的Rcpp包在C++中有一些矢量化操作,模仿了一些操作;参见Rcpp-sugar pdf小插图了解更多信息(和/或我们在Rcpp上的一些演讲)。

创建一个可以使用匹配值初始化的函子对象,并使用 std::for_each 对列表进行迭代。 所以例如:

vector<int> values;
//fill your vector with values;
struct match_functor
{
    vector<int> value_array;
    int match_value;
    match_functor(int value): match_value(value) {}
    void operator() (int input_value)
    {
        if(match_value == input_value)
            value_array.push_back(input_value);
    }
};
match_functor matches(1);
std::for_each(values.begin(), values.end(), matches);

现在可以使用 matches.value_array[INDEX] 访问结果值数组。

作为替代方法,如果您只想获得原始向量的指示,而不是实际值,那么您可以对函子对象执行以下操作:

struct match_functor
{
    vector<int> index_array;
    int match_value;
    int index;
    match_functor(int value): match_value(value), index(0) {}
    void operator() (int input_value)
    {
        if(match_value == input_value)
            index_array.push_back(index);
        index++;
    }
};
match_functor matches(1);
matches = std::for_each(values.begin(), values.end(), matches);

现在matches.index_array[INDEX]将保存与值1匹配的原始向量的指示,而不是原始向量的实际值。

算法std::find_if应该可以解决问题 - 结合我应该添加的循环。