searching and then modifying element in a list
hi,
i have a set of numbers. now i want to search for a number and modify the match, if any found. so i code something like this...
set<int> list;
list.insert(1);
list.insert(2);
list.insert(3);
....
set<int>::iterator match = list.find(3);
if(match != list.end()) { // there is a match
*match = 7; // i want to modify the match to 7
}
however, it gives me a error since find() returns a const iterator and the contents cant be modifed.
do i need to convert my const interator (match) to a regular iterator. if so, how? are there other efficient ways to accomplish my goal?
thanks,
amit
Re: searching and then modifying element in a list
A set is acontainer that contains a sorted set of unique objects.
If you would change the value where the iterator points to the container would not be sorted anymore.
You have to remove the element that was found and insert another object.
Kurt
Re: searching and then modifying element in a list
SET is associative container it doesnt allow to change the value. the best way is delete the element & insert new one.
If you need to change the value ur container selection is wrong. Try to use some other container
Vinod
Re: searching and then modifying element in a list
Re: searching and then modifying element in a list
Quote:
Originally Posted by ausinha
what if i use a hash?
Probably not a good idea, because hash maps are not sorted in any way.
So if your data needs to be in a particular order, it's not going to work.
But if you are only interested in storing, searching, and retrieving
unordered data then by all means use a hash map. It has the
quickest average case time complexity, O(1) constant time, for all
three operations.
Re: searching and then modifying element in a list
Why not u r using it in a Simple Way
Code:
list <int> c1, c2;
list <int>::iterator Iter;
c1.push_back( 10 );
c1.push_back( 20 );
c1.push_back( 30 );
cout << "c1 =";
for ( Iter = c1.begin( ); Iter != c1.end( ); Iter++ )
{
if(*Iter==20)
{
*Iter = 40;
}
}
for ( Iter = c1.begin( ); Iter != c1.end( ); Iter++ )
{
cout<<*Iter <<" "; //will print now 10 40 30
}
cout << endl;