可以通过复制来初始化集合吗?
Can one initialize a set by copying?
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] 是越界访问。先放一个元素!
相关文章:
- 是否可以初始化不可复制类型的成员变量(或基类)
- C++使用整数的压缩数组初始化对象
- C++初始化基类
- 多成员Constexpr结构初始化
- 复制列表初始化的隐式转换的等级是多少
- 内联映射初始化的动态atexit析构函数崩溃
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 没有用于初始化C++中的变量模板的匹配构造函数
- 在未初始化映射的情况下,将值插入到映射的映射中
- C++成员初始化
- 可以通过复制来初始化集合吗?
- 使用依赖于 "this" C++ 的比较结构初始化集合
- 在C 中初始化集合迭代器
- 用C++中的比较器初始化集合
- 如何初始化具有特定数量元素的集合
- 使用集合作为与类一起初始化的属性
- 在没有默认构造函数时初始化 STL 集合元素(不是指针)
- Visual Studio - 如何在 MS 编译器中使用数组初始化C++向量/集合
- 如何使用另一个类的静态集合初始化集合