可以通过复制来初始化集合吗?

Can one initialize a set by copying?

本文关键字:集合 初始化 复制 可以通过      更新时间:2023-10-16
std::vector<std::set<int>> m;
m[0].insert(0);
m[0].insert(1);
std::set<int> n = m[0]; // is this allowed?
for(std::set<int>::iterator iter = n.begin(); iter < n.end(); iter++)  // error in this line, "<" not defined.

我可以通过直接复制来初始化集吗?最后一行有错误。

我可以通过直接复制来初始化集合吗?

从 cpp 首选项:

从各种数据源构造新容器,并可选择使用用户提供的分配器分配或比较函数对象组合
...
3(复制构造函数。使用其他内容的副本构造容器。如果未提供分配器,则通过调用 std::allocator_traits::select_on_container_copy_construction(other.get_allocator((( 获取分配器。

代码中的问题:你定义了一个没有任何元素的向量,并尝试将元素更改为 0。
两种解决方案:

// Solution 1
std::vector<std::set<int>> m(1); // Define vector with one element
// Solution 2
std::vector<std::set<int>> m;
m.push_back(std::set<int>()); // Add new element to the vector with push_back
m.emplace_back(); // Add new element to the vector with emplace_back (recommended)

编辑:

对于最后一行,将<更改为!=

for(std::set<int>::iterator iter = n.begin(); iter != n.end(); iter++)
  • 我可以通过直接复制来初始化集合吗?

是的

  • 最后一行有错误

编写的 forloop 使用 "<" 运算符来比较iter是否仍然小于集合中的结束迭代器。但是迭代器没有定义"<"运算符。这会导致错误消息。请改用!=

  • 此外,您的向量不包含元素。 所以 m[0] 是越界访问。先放一个元素!