C++11 为什么我的搜索功能不能按预期工作?我如何修复它?
我正在尝试创建一个比较搜索函数,它可以根据字符将两个字符串比较在一起。例如: 输入:“ca” 姓氏字段下的结构向量内容(排序向量)(索引/值):0/“汽车”,1/“道路” 结果:“在索引0处找到名称-车辆” 我希望用户能够使用任意数量的字符。然后,程序应将提供的搜索条件与向量的内容进行比较,并返回任何匹配项的索引 到目前为止,我已经尝试实现这个算法,但没有成功,下面是我的代码。我对C++也是很新的。C++11 为什么我的搜索功能不能按预期工作?我如何修复它?,c++11,C++11,我正在尝试创建一个比较搜索函数,它可以根据字符将两个字符串比较在一起。例如: 输入:“ca” 姓氏字段下的结构向量内容(排序向量)(索引/值):0/“汽车”,1/“道路” 结果:“在索引0处找到名称-车辆” 我希望用户能够使用任意数量的字符。然后,程序应将提供的搜索条件与向量的内容进行比较,并返回任何匹配项的索引 到目前为止,我已经尝试实现这个算法,但没有成功,下面是我的代码。我对C++也是很新的。 // Function for searching through an array for a
// Function for searching through an array for a string value.
int searchArray(std::vector<playerdata> (&people), std::string name) {
int loc = -1;
int counter = 0;
int index = 0;
//when loc is no longer -1, that means the person has been found
for (int i = 0; i < people.size(); i++)
for(int k = 0; k < name.length(); k++) {
std::cout << name[k-1] << std::endl;
std::cout << people[i].lastname[k-1] << std::endl;
std::cout << counter << std::endl;
std::cout << "" << std::endl;
if(name[k-1] == people[i].lastname[k-1]) {
counter++;
}
if(counter == name.length()) {
loc = i;
break;
}
}
//if (people[i].lastname.compare(name) == 0)
//loc = i;
return loc;
}
编辑:正如您可以从我的控制台输出中看到的那样,代码返回的是真正的比较,而它不应该这样做。一个例子是is(e==n)的最后一次比较。答案应该是错的,但它总是返回真的
使用注释中建议的代码后,我仍然无法使代码按预期工作,并出现以下错误:
||=== Build file: "no target" in "no project" (compiler: unknown) ===|
E:\Coding\Cplus_work\assignmentseven.cpp||In function 'int main()':|
E:\Coding\Cplus_work\assignmentseven.cpp|68|warning: NULL used in arithmetic [-Wpointer-arith]|
E:\Coding\Cplus_work\assignmentseven.cpp|158|warning: NULL used in arithmetic [-Wpointer-arith]|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\predefined_ops.h||In instantiation of 'bool __gnu_cxx::__ops::_Iter_pred<_Predicate>::operator()(_Iterator) [with _Iterator = __gnu_cxx::__normal_iterator<playerdata*, std::vector<playerdata> >; _Predicate = searchArray(std::vector<playerdata>&, std::__cxx11::string&)::<lambda(std::__cxx11::string&)>]':|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\stl_algo.h|120|required from '_RandomAccessIterator std::__find_if(_RandomAccessIterator, _RandomAccessIterator, _Predicate, std::random_access_iterator_tag) [with _RandomAccessIterator = __gnu_cxx::__normal_iterator<playerdata*, std::vector<playerdata> >; _Predicate = __gnu_cxx::__ops::_Iter_pred<searchArray(std::vector<playerdata>&, std::__cxx11::string&)::<lambda(std::__cxx11::string&)> >]'|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\stl_algo.h|161|required from '_Iterator std::__find_if(_Iterator, _Iterator, _Predicate) [with _Iterator = __gnu_cxx::__normal_iterator<playerdata*, std::vector<playerdata> >; _Predicate = __gnu_cxx::__ops::_Iter_pred<searchArray(std::vector<playerdata>&, std::__cxx11::string&)::<lambda(std::__cxx11::string&)> >]'|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\stl_algo.h|3930|required from '_IIter std::find_if(_IIter, _IIter, _Predicate) [with _IIter = __gnu_cxx::__normal_iterator<playerdata*, std::vector<playerdata> >; _Predicate = searchArray(std::vector<playerdata>&, std::__cxx11::string&)::<lambda(std::__cxx11::string&)>]'|
E:\Coding\Cplus_work\assignmentseven.cpp|35|required from here|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\predefined_ops.h|283|error: no match for call to '(searchArray(std::vector<playerdata>&, std::__cxx11::string&)::<lambda(std::__cxx11::string&)>) (playerdata&)'|
E:\Coding\Cplus_work\assignmentseven.cpp|33|note: candidate: 'searchArray(std::vector<playerdata>&, std::__cxx11::string&)::<lambda(std::__cxx11::string&)>'|
E:\Coding\Cplus_work\assignmentseven.cpp|33|note: no known conversion for argument 1 from 'playerdata' to 'std::__cxx11::string&' {aka 'std::__cxx11::basic_string<char>&'}|
E:\Coding\Cplus_work\assignmentseven.cpp||In function 'bool sortArray(const playerdata&, const playerdata&)':|
E:\Coding\Cplus_work\assignmentseven.cpp|28|warning: control reaches end of non-void function [-Wreturn-type]|
||=== Build failed: 1 error(s), 8 warning(s) (0 minute(s), 0 second(s)) ===|
||===生成文件:“无项目”中的“无目标”(编译器:未知)===|
E:\Coding\Cplus_work\assignmentseven.cpp |在函数“int main()”中:|
E:\Coding\Cplus|u work\assignmentseven.cpp | 68 |警告:算术中使用NULL[-Wpointer arith]|
E:\Coding\Cplus_work\assignmentseven.cpp | 158 |警告:算术中使用NULL[-Wpointer arith]|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\prefined_ops.h | | |在'bool_ugnu cxx:::u ops::_Iter_pred::operator()(_Iterator)[with u Iterator=u gnu cxx::u normal Iterator;_谓词=searray(std::vector&,std:uuux11::string&]:]|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\stl|u algo.h | 120 |来自“_randomAccessIteratorstd::u find_if(_RandomAccessIterator,_RandomAccessIterator,_Predicate,std::random_accessIterator(标记)[带u RandomAccessIterator=u gnu cxx::u normal iterator;u谓词=u gnu cxx:u ops:)|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\stl|u algo.h | 161 |来自“_iteratorstd::u find_if(_Iterator,_Iterator,_Predicate)[带u Iterator=u gnu cxx::u normal Iterator;u predicator=u gnu cxx:u-gnu-cxx:u-gnu-cxx:u-Iter::u-ops:u-pred:u-Iter:|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\stl_algo.h | 3930 |来自“_iiterstd::find_if(_IIter,_IIter,_IIter,_Predicate)[with IIter=u gnu cxx::u normal iterator;_Predicate=searray(std::vector&,std:uuuuuucx11::string&)]:]|
E:\Coding\Cplus|u work\assignmentseven.cpp | 35 |此处必填|
c:\mingw\lib\gcc\mingw32\8.2.0\include\c++\bits\predefined_ops.h | 283 |错误:调用(searchArray(std::vector&,std:uucxx11::string&):(playerdata&)不匹配|
E:\Coding\Cplus_work\assignmentseven.cpp | 33 |注:候选者:'searchArray(std::vector&,std::uu cxx11::string&):'|
E:\Coding\Cplus_work\assignmentseven.cpp | 33 |注:参数1从'playerdata'到'std::uuuuucx11::string&'{aka'std::uuucx11::basic_string&')没有已知的转换|
E:\Coding\Cplus_work\assignmentseven.cpp |在函数“bool sortArray(const playerdata&,const playerdata&)”中:|
E:\Coding\Cplus|u work\assignmentseven.cpp | 28 |警告:控件到达非无效函数的末尾[-Wreturn type]|
||==生成失败:1个错误,8个警告(0分钟,0秒))===|
我使用的确切代码是:
// Function for searching through an array for a string value.
int searchArray(std::vector<playerdata> (&people), std::string (&name))
{
auto it = std::find_if(people.begin(), people.end(), [&name](std::string& person){
return person.find(name) != std::string::npos;
});
if(it != people.end()) {
return std::distance(people.begin(), it);
} else {
return -1;
}
}
//用于在数组中搜索字符串值的函数。
int searchArray(std::vector(&people),std::string(&name))
{
auto it=std::find_if(people.begin()、people.end()、[&name](std::string&person){
返回person.find(name)!=std::string::npos;
});
if(it!=people.end()){
return std::distance(people.begin(),it);
}否则{
返回-1;
}
}
主要问题可能是当k=0
时,您试图访问name[k-1]
和lastname[k-1]
,这会导致UB
在继续你的工作之前,开始学习。考虑到这一点,仅使用find_if
和std::string::find
:
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
struct playerdata
{
std::string lastname;
playerdata(std::string lastname) :
lastname(std::move(lastname))
{
}
};
int searchArray(std::vector<playerdata>& people, const std::string& name)
{
auto it = std::find_if(people.cbegin(), people.cend(), [&name](const playerdata& player){
return player.lastname.find(name) != std::string::npos;
});
if(it != people.end())
return std::distance(people.cbegin(), it);
else
return -1;
}
#include可能主要问题是当k=0
时,您试图访问name[k-1]
和lastname[k-1]
,这会导致UB
在继续你的工作之前,开始学习。考虑到这一点,仅使用find_if
和std::string::find
:
#include <algorithm>
#include <iostream>
#include <vector>
#include <string>
struct playerdata
{
std::string lastname;
playerdata(std::string lastname) :
lastname(std::move(lastname))
{
}
};
int searchArray(std::vector<playerdata>& people, const std::string& name)
{
auto it = std::find_if(people.cbegin(), people.cend(), [&name](const playerdata& player){
return player.lastname.find(name) != std::string::npos;
});
if(it != people.end())
return std::distance(people.cbegin(), it);
else
return -1;
}
#包括
首先,你的解决方法是正确的,但需要一些技巧
改进
我假设你不想用正则表达式或模板C++函数来解决它。
哪种方式更好
您可能对中断声明有误解,这会影响
只有它被写入的循环
我已经在评论中解释了缺失点和需要改进的地方
线条
因为你没有详细说明所有的细节,我不得不假设它们
`
SearchArray(std::vector&people,const std::string&keyWord)
{
int loc=-1;
//使用更好的变量名来解释其用途,而不是'i'`
//所以你和其他像我们这样的人可以更快地理解它的意思
对于(int-vectorIndex=0;vectorIndexpeople[vectorIndex].lastname.length())
{
继续;
}
int计数器=0;
int charIndexKeyWord=0;
//使用更好的变量名来解释其用途,而不是'k'`
对于(int charIndexIarget=0;charIndexIarget首先,你的解决方法是正确的,但需要一些技巧
改进
我假设你不想用正则表达式来解决它
SearchArray(std::vector<playerdata>& people, const std::string& keyWord)
{
int loc = -1;
// Use a better variable name to explain its purpose instead of `i`
// so you and other people like us can understand its meaning much faster
for (int vectorIndex = 0; vectorIndex < people.size(); vectorIndex++)
{
// if length of the name is bigger than a lastname it can`t be a match so just continue
if (keyWord.length() > people[vectorIndex].lastname.length())
{
continue;
}
int counter = 0;
int charIndexKeyWord = 0;
// Use a better variable name to explain its purpose instead of `k`
for (int charIndexIarget = 0; charIndexIarget < people[vectorIndex].lastname.length(); charIndexIarget++)
{
// Your for loop starts from 0 but you're trying to use [k-1] in your code
// you shouldn't do that, because in the first iteration of the loop it will indicate -1 [k-1]
// but it starts with 0,
//std::cout << keyWord[charIndexKeyWord] << std::endl;
//std::cout << people[vectorIndex].lastname[charIndexIarget] << std::endl;
//std::cout << counter << std::endl;
//std::cout << "" << std::endl;
// This is part of your code which needs improvment
if (keyWord[charIndexKeyWord] == people[vectorIndex].lastname[charIndexIarget])
{
counter++;
charIndexKeyWord++;
}
else
{
// If you keep your code as it is, it will may also consider matches like susnhine `sun` because
// so you need to make some improvements to get rid of it.
// if you have already founded a match but next word is not a match then you need to start looking from the beginning
if (counter != 0)
{
counter = 0;
charIndexKeyWord = 0;
}
}
if (counter == keyWord.length())
{
loc = vectorIndex;
}
}
if (loc != -1)
{
break;
}
}
return loc;