开发者

binary_search not working for a vector<string>

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namesp开发者_JAVA百科ace 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 ?


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


collection must be sorted before doing binary_search. is it?


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


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


To make it work, you must use the binary_search with function created to compare strings.

For example, in your case:

if((binary_search(decrypt.begin(), decrypt.end(), **temp.c_str(),compareFunction**)) == true) ++co;

You must declare compareFunction in this way:

bool compareFunction(string aux1,string aux2)
{
  if(strcmp(aux1.c_str(),aux2.c_str()) <0)
  {
    return true;
  }
  else
  {
    return false;
  }
}

you can see the declaration of this method here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜