2011-05-23 39 views
5

让我解释 '这' 的功能是什么:是否有在C/C++相同功能以GNU-R,其中()?

从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类似的功能++?

感谢您的帮助

rinni

+0

['std :: find_if'](http://en.cppreference.com/w/cpp/algorithm/find)或['std :: copy_if'](http://en.cppreference.com/ w/cpp/algorithm/copy)取决于你想要用它做什么。 (或其他几个图书馆电话) – 2012-12-20 17:40:57

回答

6

你必须明白,R是矢量化,而C则首先适用于原子化的个人数据片段:一个intdouble,...

使用C++,你可以看看STL算法与您接近这个。

最后,在R和C++交叉点,我们的Rcpp封装具有在C++一些矢量操作模仿一些操作;请参阅Rcpp-sugar pdf小插图了解更多(和/或我们有关Rcpp的一些会谈)。

+0

你是绝对正确的。我的拳头方法是以R为中心的。猜猜我必须尝试一下C++的观点。 – rinni 2011-05-24 08:39:58

2

算法std::find_if应该做的伎俩 - 连同一个循环我要补充。

3

创建一个仿函数对象,您可以用匹配值初始化,以及迭代器来使用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]访问。

作为替代方案,如果你只是想有原始载体的indicies,而不是实际值,那么你可以为你的仿函数对象做这样的事情:

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,而不是实际的数值,所述indicies。

+1

你的第一个代码片段只是'的std :: remove_copy_if'的更复杂的替代品。 – 2011-05-23 14:15:03

+0

虽然它并没有删除任何值,但它将原始向量中发生次数的所需值复制N次。 – Jason 2011-05-23 14:21:40

+2

@Jason是的,它将输入向量中的值复制到其他值,从而删除(不复制)不符合某些谓词的任何值。这就是'std :: remove_copy_if'的作用。 – 2011-05-23 14:59:33

相关问题