类 C++ 的 iota 增量向量

iota increment vector of a class c++

本文关键字:向量 iota C++      更新时间:2023-10-16

我最近一直在利用 <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 );
}