我发现自己需要返回两个向量的交集大小:
std::vector<int> A_, B_
Run Code Online (Sandbox Code Playgroud)
我不需要相交的值,只需要集合的大小.这个功能需要被调用很多次.这是对(数学)图形/网络进行更大模拟的一部分.
我的工作条件是:
我的第一次尝试,使用一个天真的循环,在下面.但我认为这可能还不够.我假设......由于重复的排序和分配,std :: set_intersection将过于繁重.
int vec_intersect(const std::vector<int>& A_, const std::vector<int>& B_) {
int c_count=0;
for(std::vector<int>::const_iterator it = A_.begin(); it != A_.end(); ++it){
for(std::vector<int>::const_iterator itb = B_.begin(); itb != B_.end(); ++itb){
if(*it==*itb) ++c_count;
}
}
return c_count;
}
Run Code Online (Sandbox Code Playgroud)
鉴于我的上述条件,我还能如何实现这一点以获得速度,相对容易?我应该考虑哈希表还是使用排序和STL,或者不同的容器?
我正在寻找最佳/正确的方法来确定容器是否实现随机元素访问.at().在不同(stl)容器相对于彼此进行排序的情况下(比如对容器进行排序std::vector<int>,相对于std::vector<double>),我做了以下事情:
std::sort(toOrder.begin(), toOrder.end(), [&orderBy](int i, int j) -> bool {
return orderBy.at(i) > orderBy.at(j);
});
Run Code Online (Sandbox Code Playgroud)
哪里
std::vector<int> toOrder;
std::vector<double> orderBy
Run Code Online (Sandbox Code Playgroud)
我可以将它包装在模板函数中,但我不确定限制或测试具有随机访问迭代器/ .at()的容器的最佳方法(当它们没有时,需要做一些昂贵的事情).
我有这个
#include <iostream>
#include <vector>
#include <algorithm>
#include <unordered_set>
template <typename T, typename U>
void sorty(T& a, U const x) {
std::sort(a.begin(), a.end(),
[&x](int i, int j) -> bool { return x.at(i) > x.at(j); });
}
int main() {
std::vector<int> toOrder(10);
std::iota(toOrder.begin(), toOrder.end(), 0);
std::vector<double> orderBy{0.2, 9.8, 4.0, 0.01, 15.1,
3.3, 9.01, …Run Code Online (Sandbox Code Playgroud) 在我开始更新gcc之前,有没有人真正尝试过这个,并且他们可以确认从源代码构建R是需要更新用于使用Rcpp编译c ++代码的gcc版本(即不一定用于包创作,当然不适用于CRAN有效包)?
请参阅Dirk对此问题的回答,以及原始海报如何在Windows上使用gc 4.8.1和Rcpp的后续评论.
c++ ×3
stl ×2
c++11 ×1
containers ×1
gcc ×1
intersection ×1
performance ×1
r ×1
rcpp ×1
templates ×1
vector ×1
windows ×1