+ 3

Array function nested loops

I have created an nested array for loop that can compare elements within each other. But I want to create a function that represents the inner loop of my nested function. Unfortuantely, I have been very successful. Here is my program so far: #include <iostream> Using namespace std; bool matchingelements(const int hand[]); int helpcomparingArray(const int hand[]); int main (); Int array[7] = {2,5,3,2,9,7,8}; if (matchingelement(array)) { cout << "there are 2 matching numbers in this array" << endl; } } bool matchingelements(const int hand[]){ int Count =0; for (int a=0; a<7;++a){ for (int b=0; b<7;++b){ if (a==b) continue; if (array[a] == array[b]) Count ++; } } if (Count ==2){ return true; } else { return false; } } } int helpcomparingArray(const int hand[]); I want to create a function to simplify nesting loop (speifically) the inner loop. But i dont know how.

13th Sep 2016, 6:33 PM
Hakatek
1 Answer
0
// solution // http://melpon.org/wandbox/permlink/djVjx6sonYugX4ih #include <iostream> #include <vector> #include <map> #include <algorithm> using namespace std; bool matchingelements(vector<int> const& vec){ map<int,int> m; for(auto const& item : vec){ // access via [] creates a default constructed element in this case 0!!!! m[item]++; } for_each(m.begin(),m.end(),[](auto const& pair){ cout << pair.first << " " << pair.second << endl; }); //print the map for debug/understanding purpose return vec.size() > m.size(); //when the map has less elements than the vector there must be at least 2 matching elements! //you could itereate over the map and check for pair second. } int main (){ vector<int> vec = {2,5,3,2,9,7,8}; if (matchingelements(vec)) { cout << "there are 2 matching numbers in this array" << endl; } }
6th Oct 2016, 7:44 PM
Jan Christopher
Jan Christopher - avatar