STL::set. How can I change the value that an iterator point to?

Dec 2, 2009 at 5:51pm
When we iterate through the set, can we somehow change the value of the object in the set? So I have a class Student which have a name and a num.
Add all these student in the set. When I iterate through the set, how can I change the value of "num"? In another word, I want to do something like this
 
Interator it->num = 10; //Sucks!!! this does not work :( :( 

Below is my code. Thank you
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <set>
#include <iostream>
using namespace std;

class Student{
   public:
      int num;
      string name;
};


class Comp
{
   public:
      bool operator()(Student s1, Student s2)
      {
         if(s1.num < s2.num )
            return true;
         else
            return false;
      }
};

int main()
{
   set<Student, Comp> myStudent;
   Student student1;
   Student student2;
   student1.num = 4;
   student1.name = "Tom";
   student2.num = 7;
   student2.name = "Arab";
   myStudent.insert(student2);
   myStudent.insert(student1);
   
   set<Student, Comp>::iterator it;
   for(it=myStudent.begin(); it!=myStudent.end(); it++)
   {
      (*it).num = 10;
      cout<<it->num<<"   "<<it->name<<endl;
   }
}


So I want the output to come out like this
1
2
10  Tom
10  Arab

Instead of
1
2
4  Tom
7  Arab

I know change the value of "num" is a bad idea, because the set will not reorder by itself, but I just want to know and plus what if I want to change Tom and Arab instead of num. Please help
Dec 2, 2009 at 6:14pm
I do that all the time with iterators for vectors/maps. I hardly use sets, so are you getting a compile error or anything?
Dec 2, 2009 at 6:47pm
I think it is the problem with set. It seems to me that set::iterator return a const void * instead of void*, so when I try to do memcpy, it complain that "invalid conversion from const void * to void*". It sucks!!! I guess I will just changed my container to list to make my life easier.
The reason I didnt use list in the beginning is because, I have to keep elements in my container in order. Since set always keep all it element in order and simply insert new element into the right place, so it is O(n) instead of sorting the elements every time like list O(nlog(n)). But oh well
Dec 2, 2009 at 9:28pm
You can't.

set's iterator is a typedef of its const_iterator because allowing the user to change the value of an
element through an iterator could potentially break set's guarantee of uniqueness of all elements.

Dec 2, 2009 at 11:56pm
Not only uniqueness, but sooner the sorted order.
Multiset doesn't require uniqueness but has only const_iterator.
Topic archived. No new replies allowed.