how to add an element to the string position of a vector

Viewed 56

I want the add function in the Carnet class to add a number to a position (position to be a string) and when I display myclass << ["string"] to display the number

the problem is that when I run the instructions in the main it shows me wrong(7,7,7), instead of showing me 7,9,10

I think the problem is saving in vector but I do not know how to fix it, I tried this:

  this->insert(this->begin() + atoi(a.c_str()), b);
#include <iostream>
#include <vector>

using namespace std;

template <typename ElementT>
class Carnet : public vector<ElementT> {

public:
    Carnet() : vector<ElementT>() {

    }
    int operator[] (string materie) {
        return this->at(atoi(materie.c_str()));
    }
    Carnet add(string a, int b) {
        this->insert(this->begin() + atoi(a.c_str()), b);
        return *this;
    }
    Carnet removeLast() {
        this->pop_back();
        return *this;
    }
   
};

int main()
{
    Carnet<int> cat;
    cat.add("SDA", 9);
    cat.add("OOP",7).add("FP", 10);
    cout<<cat["OOP"];
    cout<<cat["SDA"];
    cout<<cat["FP"];
    cat.removeLast().removeLast();
  
    return 0;
}


1 Answers

The problem is here:

Carnet add(string a, int b) {
    this->insert(this->begin() + atoi(a.c_str()), b);
    return *this;

When you returning by value, you are making a copy, which means here

cat.add("OOP",7).add("FP", 10);

the second add will operate on a new object instead of on cat.

You should use a reference instead:

Carnet& add(string a, int b) {

Same problem with removeLast.

Edit: Also, deriving from vector is generally not advisable. You should consider using composition instead.

Edit 2: There is a more fundamental problem. atoi should only ever return 0 here, because you never present it with any number strings.

It is not entirely clear what you are intending to do here. But maybe a vector is the wrong container? It seems you want to associate a number with a string. A std::map<std::string, int> could do the job.

Related