迭代C++向量的最快方法

Coo*_*oli -3 c++ iteration vector time-limiting

我正在寻找有关矢量迭代的一些提示.我正在尝试完成一个挑战,你必须实现一个函数(SumOfTwo),它接受两个向量和一个和作为参数,并且必须检查两个向量中是否有任何数字对,如果添加可以给出总和作为参数传递.

我的功能很好,除了它不包括500毫秒的时间限制.我觉得有一个更好的方法来迭代两个向量而不是两个for循环,但我觉得非常卡住......

bool sumOfTwo(std::vector<int> a, std::vector<int> b, int v) {
    if((a.empty()) || b.empty()){
        return false;
    }
    for (std::vector<int>::iterator it1 = a.begin(); it1<=a.end(); ++it1)     {
            for (std::vector<int>::iterator it2 = b.begin(); it2<=b.end(); ++it2) {
                if ((*it1 + *it2) == v){
                    return true;
                }
            }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

Cur*_*ous 5

关于风格提示,请将代码更改为以下内容(为了提高效率和整洁度)

bool sumOfTwo(const std::vector<int>& a, const std::vector<int>& b, int v) {
    for (auto i1 : a)     {
            for (auto i2 : b) {
                if ((i1 + i2) == v){
                    return true;
                }
            }
    }
    return false;
}
Run Code Online (Sandbox Code Playgroud)

考虑使用std::unordered_set和交叉引用来查找是否可以获得最大效率.请记住,a中的查找std::unordered_set是O(1)

  • @downvoter,请评论我可以做些什么来改善这个答案? (2认同)
  • @Curious我不是TA.如果一个成年人在SO上提出问题,如果它属于网站的范围并且海报已经给予他/她的诚意努力,我将回答它. (2认同)