### c++

#### Quickest way to iterate in a C++ vector

I was looking for some tips regarding vector iteration. I am trying to fulfill a challenge, in which you have to implement a function (SumOfTwo) that takes two vectors and a sum as arguments and has to check if there is any pair of numbers in the two vectors that if added can give the sum that is passed as an argument. My function works fine, except that it doesn't cover the time limitation which is 500ms. i feel that there is a better way to iterate through two vectors than two for loops, but I feel very stuck... 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; }

Why is the algorithm slow? Currently you're iterating over two vectors, but you're doing nested iteration. Let's call the lengths of the vectors m and n (arbitrarily). Your current algorithm is O(n*m), which is quite slow for large vectors. If m = n = 1000, in the worst-case (no two elements sum to v), you're doing millions of operations -- whew! How can I improve the performance? I can think of one immense speedup: given a vector, a, a vector b, and a desired sum v, you could create a set of numbers from the element-wise difference of v and a and check if any of the values in b are in the set. The pseudocode is: if a.empty or b.empty: return false set = emptySet for e in a: set.add(v - e) for e in b: if e in set: return true return false Lookups in an unordered set should be O(1), so this is now an O(max(m, n)) algorithm where m is length of a and n is length of b. If m = n = 1000, in the worst-case you're now doing thousands of operations -- much better, right? Implementing this in C++ is left to the reader. :) Hint: passing by reference is a good idea for vectors.

Regarding just style tips, change your code to the following (for efficiency and neatness) 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; } Consider using an std::unordered_set and cross referencing that to find whether a sum is possible for maximal efficiency. Remember that lookups in an std::unordered_set are O(1)

Thank you all for your great help! The way i solved the time restriction is: bool sumOfTwo(std::vector<int>& a, std::vector<int>& b, int v) { if((a.empty()) || b.empty()){ return false; } std::unordered_set<int> s; for (const auto i : a) { s.insert(v-i); } for (const auto i : b) { auto search = s.find(i); if (search != s.end()) { return true; } } return false; }

### Related Links

How to construct a list of files from the `start group … end group` linker option

How to exclude isolated nodes from generated Doxygen Class Hierarchy

Why might compiling with -march=native cause “pointer being freed was not allocated”?

Cant access correct number of vertices for a 3d model (.OBJ) using Assimp

In using-declaration, can dependent names render to constructors after template substitution?

How to add C++ files to the Objective-C/C++ OpenGL ES project

Using Eigen in custom tensorflow op

Create JSON structure based on input variables

C++ range for loop different than regular for loop [closed]

C++ boost thread causes segmentation fault when instantiated twice

c++ - 3 bears in a vector of a struct, how can I change this code so the specific bear at the exit is removed?

Reading from excel/text file without skipping whitespaces unless made by a tab

How to initialize const size array in constructor without explicitly stating the size in class declaration?

Reading txt file into 2d array C++

How can I mark a function with an attribute conditionally on the value of a parameter?

Read a text file and store into two different arrays: a string array and float array