LMHmedchem

May 7th, 2011, 08:47 PM

I have some vectors to evaluate and develop a list of values that occur in more than one element.

This is the simplest case. I have a vector,

std::vector<int> vec1;

vec1[0]=5;

vec1[1]=5;

I need to know that that 5 occurs twice in the vector. If I do a double loop,

std::vector<int> occurs_twice;

for (i=0; i<vec1.size(); i++) {

for (j=0; j<vec1.size(); j++) {

if(vec1[i] == vec1[j]){

occurs_twice.push_back(vec1[i]);

}

}

}

The vector occurs_twice contains the value 5 in four elements.

occurs_twice[0]=5;

occurs_twice[1]=5;

occurs_twice[2]=5;

occurs_twice[3]=5;

I have identified the repeat value, but I don't have a unique list. I suppose I could check and see if 5 is already a member of occurs_twice before adding it.

for (i=0; i<vec1.size(); i++) {

for (j=0; j<vec1.size(); j++) {

if(i != j && vec1[i] == vec1[j]){

// check if vec1[i] is already on the list

m = 0;

for (k=0; k<occurs_twice.size(); k++) {

if(occurs_twice[k] == vec1[i]){ m++; }

}

if(m == 0) { occurs_twice.push_back(vec1[i]); }

}

}

}

This works, and could be cleaned up so it stops checking when m != 0, etc, but I expect there is a more efficient way to do this. Is there a library function to give values that occur more than once in a vector, or a function that would take my occurs_twice vector and return only the unique elements?

Thanks,

LMHmedchem

This is the simplest case. I have a vector,

std::vector<int> vec1;

vec1[0]=5;

vec1[1]=5;

I need to know that that 5 occurs twice in the vector. If I do a double loop,

std::vector<int> occurs_twice;

for (i=0; i<vec1.size(); i++) {

for (j=0; j<vec1.size(); j++) {

if(vec1[i] == vec1[j]){

occurs_twice.push_back(vec1[i]);

}

}

}

The vector occurs_twice contains the value 5 in four elements.

occurs_twice[0]=5;

occurs_twice[1]=5;

occurs_twice[2]=5;

occurs_twice[3]=5;

I have identified the repeat value, but I don't have a unique list. I suppose I could check and see if 5 is already a member of occurs_twice before adding it.

for (i=0; i<vec1.size(); i++) {

for (j=0; j<vec1.size(); j++) {

if(i != j && vec1[i] == vec1[j]){

// check if vec1[i] is already on the list

m = 0;

for (k=0; k<occurs_twice.size(); k++) {

if(occurs_twice[k] == vec1[i]){ m++; }

}

if(m == 0) { occurs_twice.push_back(vec1[i]); }

}

}

}

This works, and could be cleaned up so it stops checking when m != 0, etc, but I expect there is a more efficient way to do this. Is there a library function to give values that occur more than once in a vector, or a function that would take my occurs_twice vector and return only the unique elements?

Thanks,

LMHmedchem