如何在字符串向量中找到某个值

我正在尝试为分配创建程序,以从字符串向量中添加和删除字符串,但是首先我需要创建一个函数来查找向量中是否已经存在该字符串。

我已经尝试使用循环搜索向量以在每个索引处找到特定的所需字符串。我尝试添加import tkinter as ttk from datetime import datetime from PIL import ImageTk,Image root = ttk.Tk() root.geometry("800x600") root.title("New window") # -------------get date information---------- # now = datetime.now() dt_string = now.strftime("%m/%y") # grab image imagepath = "D:\\Programing\\BG_sky.jpg" background_picture = ImageTk.PhotoImage(Image.open(imagepath)) # ------------build window ------------------# date = ttk.Label(root,text=dt_string,font='helvetica') # date.pack(side="left") date.place(x=10,y=10) backgroundimage = ttk.Label(root,image=background_picture) backgroundimage.pack(side="bottom",fill="both",expand="yes") root.mainloop() 以退出该字符串(如果找到)。我不知道该函数应该为空还是布尔值。

break;

如果找到了字符串,我希望输出为true,否则显然会为false。

编辑:我忘了提到我也收到了警告:“并非所有控制路径都返回值”

yufen0312 回答:如何在字符串向量中找到某个值

您应尽可能使用std算法:

auto result = std::find(restaurantVctr.begin(),restaurantVctr.end(),targetRestnt);
return result != restaurantVctr.end();

这正是std::find的目的。

,

虽然我建议像其他人一样推荐使用std::find,但是如果您好奇代码有什么问题,那么问题出在您的else

for (i = 0; i < vctrSize; ++i) {
    if (restaurantVctr.at(i) == targetRestnt) {
        return true;
        break;
    }
    else {
        return false;
    }
}

如果向量中的第一项不等于targetRestnt,则函数返回,即结束执行。

仅当它不在整个列表中时才要返回false,也就是说,您希望执行整个循环:

for (i = 0; i < vctrSize; ++i) {
    if (restaurantVctr.at(i) == targetRestnt) {
        return true;
        // Also,you don't need a break here: you can remove it completely
        // For now,I just commented it out
        // break;
    }
}

// We didn't find it:
return false;
本文链接:https://www.f2er.com/3149748.html

大家都在问