|
-
May 10th, 2006, 02:53 PM
#1
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
-
May 10th, 2006, 03:04 PM
#2
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
-
May 10th, 2006, 03:07 PM
#3
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
-
May 10th, 2006, 08:47 PM
#4
Re: searching and then modifying element in a list
-
May 11th, 2006, 12:17 AM
#5
Re: searching and then modifying element in a list
 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.
Last edited by dcjr84; May 11th, 2006 at 12:59 AM.
Please rate my post if you felt it was helpful
-
May 11th, 2006, 01:01 AM
#6
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;
Last edited by humptydumpty; May 11th, 2006 at 01:03 AM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|