类 C++ 的 iota 增量向量
iota increment vector of a class c++
我最近一直在利用 <numeric>
iota
语句来递增 int
类型的向量。但是现在我尝试使用该语句来递增具有 2 个成员的显式类。
所以这是整数向量的用法:
vector<int> n(6);
iota(n.begin(), n.end(), 1);
假设Obj
类有一个名为 m
的整数成员。构造函数将m
初始化为其相应的整数参数。这是我现在要做的:
vector<Obj> o(6);
iota(o.begin(), o.end(), {m(1)});
我尝试使类增量重载有点像这样:
Obj& operator ++() {
*this.m++;
return *this;
}
但我认为我的构造函数不是为这种重载而设计的,反之亦然。如何修改构造函数和重载以使用 iota 递增对象成员?提前感谢!
我不确定我是否理解你的问题。以下代码是否与您想要的代码匹配?
#include <algorithm>
#include <iostream>
#include <vector>
class Object {
public:
Object(int value = 0)
: m_value(value) { }
Object& operator++() {
m_value++;
return *this;
}
int value() const {
return m_value;
}
private:
int m_value;
};
int main() {
std::vector<Object> os(10);
std::iota(os.begin(), os.end(), 0);
for(const auto & o : os) {
std::cout << o.value() << std::endl;
}
}
在OS X 4.8上使用gcc 10.7.4编译,我得到:
$ g++ iota-custom.cpp -std=c++11
$ ./a.out
0
1
2
3
4
5
6
7
8
9
更新:我更改了答案以提供评论中要求的功能:即能够更新多个字段。
以类似于以下内容的方式设置类的格式。您需要重载 ++
运算符以递增_m
和_c
。
class Obj {
private:
int _m;
char _c;
public:
Obj(int m, char c) : _m(m), _c(c)
{
}
MyClass operator++()
{
_m++;
_n++;
return *this;
}
};
以下代码将使用 6 个Obj
初始化向量o
,每个都包含从 1 开始的 _m
和_c
的升序值。
vector<Obj> o(6);
iota(o.begin(), o.end(), Obj(1, 1));
#include <numeric> // std::iota
#include <vector>
using namespace std;
class Obj
{
private:
int m_;
public:
auto value() const -> int { return m_; }
Obj( int m = 0 ): m_( m ) {}
};
auto main() -> int
{
vector<Obj> v(6);
iota( v.begin(), v.end(), 1 );
}
相关文章:
- 写入向量<向量<bool>>
- 函数向量_指针有不同的原型,我可以构建一个吗
- std::向量与传递值的动态数组
- 将值指定给向量(2D)的向量中的某个位置
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 如何使用向量的template_back函数
- 尝试通过多个向量访问变量时,向量下标超出范围
- 如何通过派生类函数更改基类中的向量
- C++从另一个类访问公共静态向量的正确方法是什么
- 如何将ampl中的集合表示为c++中的向量
- 变量没有改变?通过向量的函数调用
- 迭代时从向量和内存中删除对象
- 向量 <int> a {N, 0} 和 int arr a[N] = {0} 的时间复杂度有什么区别
- 如何为模板化对象创建模板向量?VS正在投掷C3203
- 计算排序向量的向量中唯一值的计数
- 矩阵向量乘法(cublasDgemv)返回零
- 一对向量构造函数:初始值设定项列表与显式构造
- 将结构向量排序为子组
- 在C++中调整向量中的索引
- 类 C++ 的 iota 增量向量