提问者:小点点

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


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

问题是,当我运行主要指令时,它显示我是错误的(7,7,7),而不是显示我是7,9,10

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

  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个答案

匿名用户

问题就在这里:

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

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

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

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

您应该使用引用:

Carnet& add(string a, int b) {

RemoveLast也存在同样的问题。

编辑:此外,从vector派生通常不可取。 你应该考虑使用复合。

编辑二:还有一个更根本的问题。 ATOI在这里应该只返回0,因为您从不使用任何数字字符串来表示它。

不完全清楚你在这里打算做什么。 但也许一个载体是错误的容器? 您似乎想要将数字与字符串关联起来。 std::map可以完成这项工作。