返回字符串函数

Return of a string function

本文关键字:函数 字符串 返回      更新时间:2023-10-16

我无法return某些strings是否出现多次。

即我有两个vectors,我用2nd vector搜索1st vector,如果2nd vector中的某些elements1st vector中出现不止一次,我想return错误,但由于某种原因,我只能return 1st vector中的元素是否出现多次

我的代码如下

我想return s1当元素出现不止一次时,我该怎么做,我尝试将其放在break前面,但没有奏效

std::vector<std::string> test; //vector that comes in
test.push_back("YES");
test.push_back("YES");
//test.push_back("NO");
test.push_back("NO");
std::vector<std::string> test1; // vector from DB..
test1.push_back("YES");
test1.push_back("NO");
std::string s ("Element count is fine");
std::string s1 ("Element count is incorrect");
for(int i = 0; i < test1.size(); i++)
{
    if(count(test.begin(), test.end(),test1[i]) > 1)
    {
        return s1;
    }
}
return s;

将循环更改为:

    for(int i = 0; i < test1.size(); i++)
    {
        if(count(test.begin(), test.end(),test1[i]) > 1)
        {
        //  DCS_LOG_DEBUG("Some elements have appeared more than once...");
            return s1;
        }
    }

return脱离所有控制结构并离开当前函数。您的旧代码几乎每次都返回s1,因为return s1不受if保护。

我认为代码是正确的。它在我的计算机上工作正常。也许你可以在 if 中输出一些东西,看看到底发生了什么。

    if(count(test.begin(), test.end(),test1[i]) > 1)
    {
        cout<<"The count is "<<count(test.begin(), test.end(),test1[i])<<endl;
        return s1;
    }