c++ - 如何将元素添加到 vector 的字符串位置

标签 c++ class vector operator-overloading operators

我想让Carnet类中的add函数给一个位置添加一个数字(position为字符串),当我显示myclass时<< ["string"]显示数字

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

我认为问题出在 vector 中,但我不知道如何解决,我试过这个:

  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;
}


最佳答案

问题出在这里:

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一般是不可取的。您应该考虑改用组合。

编辑 2:还有一个更根本的问题。 atoi在这里应该只返回 0,因为你永远不会用任何数字字符串来表示它。

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

关于c++ - 如何将元素添加到 vector 的字符串位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62740510/

相关文章:

c++ - 无法访问派生类中的基本 protected 成员! (在虚函数中)

c++ - 如何在 Visual Studio Code 中为 Linux 设置 Windows 子系统中的包含路径

c++ - 使用 -std=c++0x 标志编译时,Unix 宏变得未定义

python - 具有多种方法的基于类的 View 如何与 django 中的 url 一起使用?

algorithm - 向量的排列

c++ - 以与另一个列表相同的方式重新排列列表

c++ - 在可以创建彼此实例的不同类之间共享静态数据成员

r - 将数据框转换为 R 中的引用类对象

c++ - 如何初始化二维 vector

c++ - 静态 vector 的大小