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;
}
它读取两个相等的字符串列表,并应该打印出第一个列表中有多少单词也在第二个列表中找到,很简单。 没有给我expexted结果,我认为问题出在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;
}
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 ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
因为字符串没有在向量中排序。首先使用
std::sort
对它们进行排序。Because the strings are not sorted in your vectors. Sort them first using
std::sort
.在执行
binary_search
之前必须对集合进行排序。是吗?collection must be sorted before doing
binary_search
. is it?可能您的输入未排序。
binary_sort
要求您进行排序,您可以使用排序
。如果顺序不重要,更好的方法可能是使用set
和find
功能Probably, your inputs are not sorted.
binary_sort
requires you to sort, which you can do withsort
. If order doesn't matter, a better approach may be to use aset
, and thefind
functionbinary_search
假设您的向量元素已按从最低到最高的顺序排序。他们是吗?binary_search
assumes that your vectors elements are already sorted, lowest to highest. Are they?要使其正常工作,您必须使用
binary_search
with 函数来比较字符串。例如,在您的情况下:
您必须以这种方式声明
compareFunction
:您可以看到此方法的声明 这里。
To make it work, you must use the
binary_search
with function created to compare strings.For example, in your case:
You must declare
compareFunction
in this way:you can see the declaration of this method here.