简体   繁体   English

类中的 C++ 向量

[英]C++ Vectors in a Class

i am working on a worksheet i have for university and the question asks me to "Allow a user to enter 10 numbers from the keyboard into an array" however we have been told that we need to use classes and vectors for this task.我正在处理我为大学准备的工作表,问题要求我“允许用户从键盘将 10 个数字输入到数组中”,但是我们被告知我们需要使用类和向量来完成这项任务。 When i run my code i get an error stating: "Expression: Vector subscript out of range" can anyone help?当我运行我的代码时,我收到一条错误消息:“表达式:向量下标超出范围”有人可以帮忙吗?

Array.h数组.h

#include <iostream>
#include <vector>

using namespace std;

class Array
{
private:
    vector<int> lists;
public:
    void fillArray();
    void printForwards();
    void halfandHalf();
    void shiftArrayRight();

    Array();
    Array(vector<int>);
};

Array.cpp数组.cpp

#include "Array.h"
Array::Array()
{
    lists[10];
}
Array::Array(vector<int> lists)
{
    this->lists = lists;
}
void Array::fillArray()
{
    for (int i = 0; i < 10; i++)
    {
        cin >> lists[i];
    }
}
void Array::printForwards()
{
    for (int i = 0; i < 10; i++)
    {
        cout << lists[i];
    }
}

Source.cpp源文件

#include <iostream>
#include "Array.h"
using namespace std; 

int main()
{

    Array list1,list2;

    //fill array 1 
    list1.fillArray();
    //fill array 2 
    list2.fillArray();

    // print array 1 
    list1.printForwards();
    //print array 2
    list2.printForwards();

    system("pause");
    return 0;
}

Thanks in advance提前致谢

lists[10]; is not going to create a vector of size 10. It is going to try and access the 11th element of an empty vector.不会创建大小为 10 的向量。它将尝试访问空向量的第 11 个元素。 If you wanted to create a vector of size 10 then you can use如果你想创建一个大小为 10 的向量,那么你可以使用

Array::Array() : lists(std::vector<int>(10, 0)) {}

I would also suggest you change我也建议你改变

Array::Array(vector<int> lists)
{
    this->lists = lists;
}

To

Array::Array(vector<int> lists) lists(lists) {}

You should also change your for loops to use the vector size() instead of a hard coded value您还应该更改 for 循环以使用向量size()而不是硬编码值

void Array::fillArray()
{
    for (int i = 0; i < lists.size(); i++) // uses size()
    {
        cin >> lists[i];
    }
}
void Array::printForwards()
{
    for (int i = 0; i < lists.size(); i++) // uses size()
    {
        cout << lists[i];
    }
}

Or if you have C++11 or higher you can use a ranged based for loop like或者,如果您有 C++11 或更高版本,则可以使用基于范围的 for 循环,例如

void Array::fillArray()
{
    for (auto& e : lists)
    {
        cin >> e;
    }
}
void Array::printForwards()
{
    for (const auto& e : lists)
    {
        cout << e;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM