0

i cannot return if some of the strings appear more than once.

i.e i have two vectors and i search the 1st vector with the 2nd vector and if some of the elements from the 2nd vector appear more than once in the 1st vector i want to return an error but for some reason i only can return if the elements in the 1st vector do not appear more than once

my code is below

I want to return s1 when elements have appeared more than once how can i do that i tried having it infront of the break but that did not work

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;
7
  • 4
    please add some fullstops somewhere. Commented Mar 14, 2012 at 12:25
  • Look at your break. It exists the forloop, not the if statement. Commented Mar 14, 2012 at 12:27
  • "i tried having it infront of the break but that did not work" => What happened exactly? Commented Mar 14, 2012 at 12:32
  • It did not output the text for s1 @Unni Commented Mar 14, 2012 at 13:06
  • Is this the actual code you are running? It should work now with your modification. Commented Mar 14, 2012 at 13:39

2 Answers 2

2

Change the loop to:

    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 breaks out of all control structures and leaves the current function. You old code was returning s1 almost every time, because the return s1 was not guarded by the if.

Sign up to request clarification or add additional context in comments.

3 Comments

oh ok so now if i change that it will return s1 when it enters the if block hmm yeah i think it will work as it was not returning the text for s1 before
Hm it still doees not return s1 when i have my code like that either @Mankarse
Hi @Mankarse this still not working it returns s1 all the time :/
0

I think the code is right. It works fine on my computer. Maybe you can output something inside the if to see what really going on.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.