如何将元素添加到向量的字符串位置

Geo*_*sim 3 c++ class vector operator-overloading operators

我希望 Carnet 类中的 add 函数将一个数字添加到一个位置(位置为字符串),并且当我显示 myclass << ["string"] 时显示该数字

问题是,当我在 main 中运行指令时,它显示我错了(7,7,7),而不是显示我 7,9,10

我认为问题是保存在向量中,但我不知道如何解决,我试过这个:

  this->insert(this->begin() + atoi(a.c_str()), b);
Run Code Online (Sandbox Code Playgroud)
#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;
}


Run Code Online (Sandbox Code Playgroud)

Str*_*ick 5

问题在这里:

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

当您按值返回时,您正在制作副本,这意味着这里

cat.add("OOP",7).add("FP", 10);
Run Code Online (Sandbox Code Playgroud)

第二个 add 将操作一个新对象而不是 cat。

您应该改用参考:

Carnet& add(string a, int b) {
Run Code Online (Sandbox Code Playgroud)

同样的问题removeLast

编辑:此外,vector通常不建议使用源自。您应该考虑改用组合。

编辑2:有一个更基本的问题。atoi应该只在此处返回 0,因为您永远不会将任何数字字符串呈现给它。

您在这里打算做什么并不完全清楚。但也许向量是错误的容器?您似乎想将数字与字符串相关联。Astd::map<std::string, int>可以胜任。