【问题标题】:Return of a string function返回一个字符串函数
【发布时间】:2012-03-30 21:47:01
【问题描述】:

如果某些strings 出现多次,我不能return

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

我的代码在下面

当元素多次出现时我想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;

【问题讨论】:

  • 请在某处添加一些句号。
  • 看看你的休息时间。它存在 forloop,而不是 if 语句。
  • "我尝试在休息前让它出现,但没有奏效" =>到底发生了什么?
  • 它没有为 s1 @Unni 输出文本
  • 这是您正在运行的实际代码吗?它现在应该适用于您的修改。

标签: c++ string vector return


【解决方案1】:

将循环改为:

    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 块时将 return s1跨度>
  • 嗯,当我有这样的代码时,它仍然不会返回 s1 @Mankarse
  • 嗨@Mankarse 这仍然无法正常工作它一直返回s1:/
【解决方案2】:

我认为代码是正确的。它在我的电脑上运行良好。也许你可以在 if 中输出一些东西来看看到底发生了什么。

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

【讨论】:

    猜你喜欢
    • 2013-04-14
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-04
    • 1970-01-01
    相关资源
    最近更新 更多