Re: Problem using pointer...
/*
v_abs is your function fixed. I left your
original code for reference.
v_abs_nml is another way to write the same
function. Probably the most common form.
v_abs_std is another way to write the same
function, using standard library components.
It does exactly what your function does.
I'd almost bet that writing that version
of the function is your next assignment.
i_print prints a single integer on cout.
The calls to for_each in main use it
to print out the entire vector.
*/
#include <fstream> // cout, endl
#include <vector> // vector
#include <algorithm> // for_each, transform
#include <cstdlib> // abs
using namespace std;
void v_abs(vector<int>&x)
{
// int *y;
// **** y = &x;
vector< int >::iterator y = x.begin();
// while (y )
while( y != x.end() )
{
if (*y < 0)
*y *= -1;
y++;
}
}
void v_abs_nml(vector<int>&x)
{
for( vector< int >::iterator i = x.begin(); i != x.end(); ++i )
{
*i = abs( *i );
}
}
void v_abs_std( vector< int > & x )
{
transform( x.begin(), x.end(), x.begin(), abs );
}
void i_print( int x )
{
cout << x << endl;
}
int main()
{
vector< int > a;
a.push_back( -1 );
a.push_back( -2 );
a.push_back( -3 );
cout << "before" << endl;
for_each( a.begin(), a.end(), i_print );
v_abs( a );
// v_abs_nml( a );
// v_abs_std( a );
cout << "after" << endl;
for_each( a.begin(), a.end(), i_print );
}