使用C 中的向量创建整数集类别

Creating an Integer set class using vectors in C++

本文关键字:整数 创建 向量 使用      更新时间:2023-10-16

我试图编写C 中整数类的代码,并且类对象(集合)应作为向量表示:

创建一个名为IntegerSet的类。类Integerset类的每个对象都可以将整数在范围0中通过集合的大小(或100个指定)。在内部,一个集合表示为一个和零的向量。如果我不包含在集合中,则索引I处的元素设置为零,或者否则为1。

  1. 提供两个班级的构造函数。第一个构造函数采用集合的大小,并相应地初始化向量。最初,所有值都是零。默认构造函数初始化了100个元素的向量。

我对如何将类对象初始化为向量并操纵它感到困惑,因为我使用的方法给出了以下错误:没有匹配'operator []或什么也没输出。

我的代码如下:

#include<iostream>
#include<vector>
using namespace std;
class IntSet: public vector<int>
{
    public:
    //constructors: first one takes the size of a vector and initializes it accordingly,
    //second one initializes the vector to be of size 100
    IntSet(int size);
    IntSet();
    // intersection - that creates a third set that contains the common elements between two sets. 
    Intersection(IntSet& set2);
    //friend ostream& operator<<(ostream&, const )
};
IntSet::IntSet(int size)
{
    vector<int> set (size);
    for(int i=0;i<size;i++)
     set[i] =0;
}
IntSet::IntSet()
{
    vector<int> set (100);
}
/*
vector<int> IntSet::Intersection(IntSet& set2)
{
    vector<int> setOFcommon;
    for 
}
*/
int main()
{
    IntSet object(2);
    object[1]=9;
    object[2]=7;
    for(int x: object)
    cout<<x;
}

这就是如何做

class IntSet
{
public:
    IntSet(int size);
private:
    vector<int> set;
};

IntSet::IntSet(int size) : set(size)
{
    for (int i = 0; i < size; i++)
        set[i] = 0;
}

您将set向量的声明放在类中,而不是在构造函数中。在构造函数中,它只是局部变量,设置对您的课程根本没有影响。

也不从std :: vector继承。您的类具有向量,它不是一种向量。将继承用于一种关系。