#include <string>
#include <iostream>
#include <sstream>
#include "minimax.h"
#include <algorithm>
#include <iterator>
usingnamespace std;
int main (int argc, char **argv)
{
usingnamespace std;
if (argc < 2)
{
cerr << "Must supply at least one integer on the command line."
<< endl;
return -1;
}
string str;
MiniMax mnmx;
int nData = argc - 1;
int* data = newint[nData];
for (int i = 0; i < nData; ++i)
{
str = argv[i+1];
istringstream numberIn (str);
numberIn >> data[i];
mnmx.observe(data[i]);
}
int minPos = -1;
for (int i = 0; i<nData && minPos==-1; ++i)
{
if (data[i] == mnmx.getMin())
minPos = i;
}
int maxPos = -1;
for (int i = 0; i<nData && maxPos==-1; ++i)
{
if (data[i] == mnmx.getMax())
maxPos = i;
}
cout << data[0];
for (int i = 1; i<nData; ++i)
{
cout << ' ' << data[i];
}
cout << endl;
//This is fine beacuse it is not in a loop
cout << "The smallest value is " << mnmx.getMin()
<< " and can be found in position " << minPos
<< endl;
cout << "The largest value is " << mnmx.getMax()
<< " and can be found in position " << maxPos
<< endl;
return 0;
}
Specifically, I am looking at the for loop to print the array of data (lines 50-55). I want to replace this for loop with a call to a std generic function. I am thinking that I could use something like the std copy function, with something like copy ( mmmx, str, stream_iterator<string> ( cout, "\n" ));. However, this syntax is not correct. What should I be using here? Should I even be using copy at all?
Thank you for your response. Since I am working with other files, I was not able to use your entire program, but I was able to adapt your copy to work. One more question...If I were to replace the for loops in 37-42 and 43-48, would you use for_each? I was thinking originally to use bool functions for minPos and maxPos, but that would cause loops elsewhere in the program. What would you suggest?
Thank you! Maybe a dumb question here, but how do you determine exactly what parameter goes where in these generic functions? For example, how did you know to use data, data+nData, mmmx.getMax() in that particular order?
data - pointer to first element, begin of the sequence
data+nData - pointer to one past the last element, end of the sequence
this pair of iterators defines the range: [data, data+nData)
The command line arguments in argv[] are null-terminated multibyte strings (C-style strings); data is a sequence of integers. Each command line argument has to be converted from a C-style string to an int.