0

Inside a function I have a while loop that looks like the following:

void unpack(std::vector<std::string>& leftcol, std::vector<std::string>& rightcol, std::vector<std::string> origv, std::string perm) {
    ....
    while(perm != origv[0] && perm != origv[1])
    ....
}

What I'd like to do is compare perm to every element in origv. But it happens that if I do it in sequence, the while loop will loop forever. The reason for this is that perm is permuted until it matches one of the origv elements. And there's only one that matches.

Is there a way to set perm to compare with each element in origv without looping through the vector?

So if origv had three elements, I want to be able to check each element against perm in the same way the above code does for two elements.

To be clear, what I'm trying to say is I can't do something like this:

for(std::vector<std::string>::size_type i = 0; i < origv.size(); i++)
    while(perm != origv[i])
Mars
  • 4,677
  • 8
  • 43
  • 65

1 Answers1

1

I don't understand the constraint that you're describing, but the way to test whether an object compares equal to an element of a collection is to use std::find:

while (std::find(origv.begin(), origv.end(), perm) == origv.end()) {
    // perm not found
}
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • Basically I'm altering `perm` until it matches one of the string elements of the vector. There's only one element in the vector that will match it correctly after however many alterations. Anyway your method works. Thanks. – Mars Oct 22 '13 at 17:41
  • @Dochevsky Please make sure you're not having [XY problem](http://meta.stackexchange.com/q/66377/232397) – P0W Oct 22 '13 at 17:42
  • @Dochevsky - so, inside the loop you're modifying `perm`? That makes sense. – Pete Becker Oct 22 '13 at 17:44