### 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:
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;
}```

Encrypt Message

code
soft
python
ios
c
html
jquery
cloud
mobile