binary_search不适用于vector <string>

Vai*_*orn 2 c++ string vector binary-search

#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;
}
Run Code Online (Sandbox Code Playgroud)

它读取两个相等的字符串列表,并且应该打印出第一个列表中有多少单词也可以在第二个列表中找到,简单.不给我经过考验的结果,我认为问题出在binary_search中.你能告诉我为什么吗 ?

Ara*_*raK 11

因为字符串没有在向量中排序.首先使用它们排序std::sort.


And*_*rey 8

在做之前必须对集合进行排序binary_search.是吗?


Mat*_*hen 6

可能您的输入没有排序. binary_sort需要你排序,你可以做sort.如果顺序无关紧要,更好的方法可能是使用a setfind函数