Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

STL transform algorithm

Status
Not open for further replies.

jimberger

Programmer
Jul 5, 2001
222
GB
hello all,

I am trying to update each value for a set<int> with a integer already defined in the function. I have been trying to use transform algorithm. I can do

void func{
// some stuff which calculates the value of num
int num=10;

transform(set1.begin(),set1.end(),set2.begin(),add)
}

int add(int val)
{
return( val + 2);
}
so this will update every value with 2 and add to set2,but i want to be able to do this by updating each value with &quot;num&quot;
I cant see a way round this. any suggestions?
thanks


 
You need to use a function object rather than a global function. This is best practice for any kind of STL work.

Someting like this..

Code:
class AddNum
{
public:
	AddNum(int);
	int operator()(int);
private:
	int val;
};

//Initialize member value with value of num
AddNum::AddNum(int num)
:val(num)
{}


int AddNum::operator ()(int setVal)
{
	return (setVal + val);
}


int main(int argc, char* argv[])
{
	set<int> set1;
	set<int> set2;

	set1.insert(1);
	set1.insert(2);
	set1.insert(3);

	int num = 10;
	//Note the use of &quot;inserter&quot; below. set2.begin will not work
	transform(set1.begin(), set1.end(), inserter(set2, set2.end()), AddNum(num));

	set<int>::iterator i = set2.begin();
	for(; i != set2.end(); ++i)
		cout << *i << endl;

	return 0;
}
 
Status
Not open for further replies.

Similar threads

Part and Inventory Search

Sponsor

Back
Top