Element at index in a std::set?

前端 未结 6 446
太阳男子
太阳男子 2020-12-03 00:46

I\'ve stumbled upon this problem: I can\'t seem to select the item at the index\' position in a normal std::set. Is this a bug in STD?

Below a simple ex

6条回答
  •  醉梦人生
    2020-12-03 01:25

      std::set my_set;
      my_set.insert(0x4A);
      my_set.insert(0x4F);
      my_set.insert(0x4B);
      my_set.insert(0x45);
    
      int arr[my_set.size()];
    
      set::iterator it = my_set.begin();
      for (int i = 0; i < my_set.size(); i++) {
        arr[i] = *it;
        it++;
      }
      cout << arr[0];
    

    Edit: Edited code. You can't access set using index but the above method would provide an "index" i if you want to copy the elements from set into an array, provided you have created an array of sufficient size before hand.

提交回复
热议问题