In C++, you would not be using arrays (int[]
or int*
), because they are annoying in several ways: you have to pass around the SIZE
, they're usually exception-unsafe (you have to catch the exception, delete the array, then re-throw the exception), and they're hard to use as class members properly. Either use a standard library container, or an iterator range.
The idiomatic way to do what you're trying to do would be to use iterators and pairs:
template <typename IT_1, typename IT_2>
std::pair<int,int> getChange(IT1 begin, IT1 end, IT2 begin2)
{
for (; begin != end; ++begin, ++begin2)
{
if (*begin != *begin2) return std::make_pair(*begin,*begin2);
}
return std::make_pair(0,0);
}
void main() {
int myNumbers[] = {1, 0, 2, 3};
int possibilities[] = {0, 1, 2, 3};
std::pair<int,int> change = getChange(possibilities, possibilities + 4,
myNumbers);
printf("%i / %i\n", change.first, change.second);
}
Note that the second sequence (myNumbers) is expected to be as least as long as the first sequence. If you're not comfortable with iterators and function templates yet, you can always use vectors instead:
std::pair<int,int> getChange(std::vector<int> a, std::vector<int> b) {
for (int i = 0; i < a.size() && i < b.size(); ++i)
{
if (a[i] != b[i]) return std::make_pair(a[i],b[i]);
}
return std::make_pair(0,0);
}
void main() {
int _myNumbers[] = {1, 0, 2, 3};
int _possibilities[] = {0, 1, 2, 3};
std::vector<int> myNumbers(_myNumbers,_myNuymbers+4),
possibilities(_possibilities,_possibilities+4);
std::pair<int,int> change = getChange(possibilities, myNumbers);
printf("%i / %i\n", change.first, change.second);
}
While the latter may seem rather more verbose than the array version (after all, it's creating two arrays and then copying their values into the vectors), keep in mind that initializing an array from a constant is a fairly rare occurence: most of the time, arrays (and vectors) are initialized dynamically by a piece of code dedicated to just that. Such code can usually be used for both arrays and vectors with only minimal changes.
And, of course, you can typedef
both std::pair<int,int>
and std::vector<int>
to shorter names if you end up using them a lot.