samgj Posted September 29, 2012 Report Share Posted September 29, 2012 Python has an operator called in that returns true if a variable is a member of a list or array. What is the C or C++ equivilent of this? Quote Link to comment Share on other sites More sharing options...
MoLAoS Posted September 29, 2012 Report Share Posted September 29, 2012 (edited) Based on Google search of the in operator:int value[5] = { 1, 2, 3, 4, 5 };bool member;int variable;for (int i = 0; i < value.size(); ++i) { if (variable == array[i]) { member = true; return; }}Alternatively you could create your own version of the in operator for use:Note that you would need to make one for all the kinds of type reactions which is a pain so I would stick with defining it on the spot.Header file:class PythonLike {public:bool inOperatorInt(int i, int intArray[]);}cpp file:bool PythonLike::inOperatorInt(int i, int intArray[]) { for (int j = 0; j < intArray.size(); ++j) { if (i == intarray[j]) { return true; } }} Edited September 29, 2012 by MoLAoS Quote Link to comment Share on other sites More sharing options...
quantumstate Posted September 29, 2012 Report Share Posted September 29, 2012 This depends on what sort of data structure you are using. In C++ it is common to use the standard template library which has a built in find operator http://www.sgi.com/tech/stl/find.html . If you are using C then you may also be using a library to help with managing your data strcutres, which may also contain a find function. Otherwise you will have you write your own as MoLAoS suggests. Quote Link to comment Share on other sites More sharing options...
MoLAoS Posted September 30, 2012 Report Share Posted September 30, 2012 I believe vectors are basically superior arrays. They should even allow you to use a find function which is similar to in. My previous answer only applies to raw arrays. Quote Link to comment Share on other sites More sharing options...
quantumstate Posted September 30, 2012 Report Share Posted September 30, 2012 Vectors manage the memory for you. This means that they will not perform as well in some situations. If you know in advance how many items your array has then it is often more efficient to use a plain C++ array. Though most of the time this is not a concern. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.