Mars
Mars

Reputation: 4995

Specifying a range of indices

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])

Upvotes: 0

Views: 136

Answers (1)

Pete Becker
Pete Becker

Reputation: 76305

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
}

Upvotes: 1

Related Questions