【问题标题】:compilation error using iterator of set<set<int> >使用 set<set<int>> 的迭代器编译错误
【发布时间】:2017-11-23 22:09:54
【问题描述】:

我认为我没有正确使用迭代器,但我看不出我的代码有什么问题:

#include <iostream>
#include <set>
#include <ctime>
#include <cstdlib>
#include <sstream>

int main(){
  stringstream s;

  set<int> a, b, c;
  set<set<int> > d;

  set<set<int> >::iterator pos;

  srand(time(0));

  d.insert(a);
  d.insert(b);
  d.insert(c);

  for (pos = d.begin(); pos != d.end(); pos++){
      for (int i=0;i<10;i++){
          (*pos).insert(genInt(1,10));
      }
      s << "\nSet: " << endl << *pos;
  }
  s << endl;
}

我正在尝试用随机整数初始化这三个集合,同时成为另一个集合的一部分。

编译错误在(*pos).insert(genInt(1,10)):

error: no matching function for call to ‘std::set<int>::insert(int) const’

genInt(1,10) 返回 1 到 10 之间的随机整数。

int genInt(int min, int max){
int tam = max - min + 1;
return ( (rand() % tam) + min);
}

【问题讨论】:

    标签: c++ insert iterator


    【解决方案1】:

    You can't modify a set's elements。没有constinsert方法的错误是正确的。

    错误:没有匹配函数调用'std::set::insert(int)const

    pos 是set 上的迭代器,并且只能为它所引用的元素提供const 引用。因此,只能使用该引用调用 const 成员函数。 std::set 以有序的方式存储它的元素,使其能够快速找到它们。改变其中一个元素会打乱这种排序。在将它们插入更大的集合之前,您必须完全构建您的子集合。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-20
      • 2022-11-20
      • 2019-06-25
      • 1970-01-01
      • 2012-09-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多