What if I need to differentiate 0 from NULL in C++? -
** please don't criticize purpose of code itself. it's pat morin's open data structures book. not first choice, assigned reading/practice. wanted know if there way differentiate, or better way go this. textbook--> http://opendatastructures.org/ods-cpp/**
** note: i'm coming java, allowed. code still compiles, "fixes" it**
i'm surprised nothing has come before because seems such simple question. perhaps it's buried or i'm not using correct terminology.
i have loop goes through data in vector. need return value being searched if it's found. if it's not found? here code.
int find(int x) { for(int i=0;i<bag.size();i++){ // if x equal data, return data if (bag[i]==x){ return bag[i]; // ends loop 1 instance found } } // if made far, no match found. return null; }
pretty simple. let's 0 1 of valid values might need record , search for. is, returns 0, not "null". research says 1 , same. how can specify or differentiate? other returning obsqure number won't come in program because may not have luxury (like -1 or -9999999). example, searching account balance. no number impossible.
why return value searching find function? know value, 1 passed function. return position of found element instead, information more useful. when value isn't found, can return special position, -1. or can follow model of standard library , return end iterator, signifies position 1 past end of range.
Comments
Post a Comment