Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cannot access the vector members of a class

Tags:

c++

class

vector

I have tried to access the members of a class Part that are vector elements of type integer inside the vector tasks.

#include <iostream>
#include <vector>

using namespace std;

class Part{
    vector<int> tasks;
    public:

    void setTasks(void);
    void getTasks(void);
};
void Part::setTasks(void){
    vector<int>::iterator it;
    int i=1;
    for (it = this->tasks.begin(); it != this->tasks.end(); ++it)
    {
        *it=i;
        i=i+1;
    }
}

void Part::getTasks(void){
    vector<int>::iterator it;
    for (it = this->tasks.begin(); it != this->tasks.end(); ++it)
       cout<<*it<<"\t";
}
int main()
{
    Part one;
    one.setTasks();
    one.getTasks();

    return 0;
}

I am simply trying to access the values and print them yet failing. There is no compilation error. In run-time, nothing is outputted in the terminal. Where is the error?

like image 383
userzizzy Avatar asked Nov 17 '25 19:11

userzizzy


1 Answers

A default constructed vector has zero size, so the for loop in setTasks is never entered (since the begin() and end() iterators are the same at that point). If you set an initial size to the vector your code will work as intended. For instance, try adding the following at the beginning of setTasks

tasks.resize(10); // sets vector size to 10 elements, each initialized to 0

Another way to write that function would be

#include <numeric>

...

void Part::setTasks(void){
    tasks.resize(10);
    std::iota(tasks.begin(), tasks.end(), 1); // requires C++11
}

You could also set the initial size of the vector in the default constructor of Part if you wanted to. In that case add the following public constructor

Part() : tasks(10)
{}

Yet another way to achieve setting the size upon construction would be

class Part{
    vector<int> tasks = vector<int>(10); // requires C++11
like image 154
Praetorian Avatar answered Nov 19 '25 09:11

Praetorian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!