views:

97

answers:

4
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
    string temp;
    vector<string> encrypt, decrypt;
    int i,n, co=0;
    cin >> n;
    for(i=0;i<n;i++)
    {
        cin >> temp;
            encrypt.push_back(temp);
    }
    for(i=0;i<n;i++)
    {
        cin >> temp;
        decrypt.push_back(temp);
    }
    for(i=0;i<n;i++)
    {
        temp = encrypt[i];
        if((binary_search(decrypt.begin(), decrypt.end(), temp)) == true) ++co;
    }
    cout << co << endl;
    return 0;
}

It reads two equal lists of strings and should print out how many of the words in the first list are also found in the second list, simple. Not giving me the expexted results and i think the problem is in binary_search. Can you tell me why ?

+7  A: 

collection must be sorted before doing binary_search. is it?

Andrey
+4  A: 

Probably, your inputs are not sorted. binary_sort requires you to sort, which you can do with sort. If order doesn't matter, a better approach may be to use a set, and the find function

Matthew Flaschen
+7  A: 

Because the strings are not sorted in your vectors. Sort them first using std::sort.

AraK
+1. Note that if you're only looking *once* you should probably use std::find instead of std::sort and std::binary_search.
Billy ONeal
+2  A: 

binary_search assumes that your vectors elements are already sorted, lowest to highest. Are they?

Scott Smith