【问题标题】:how to add an element to the string position of a vector如何将元素添加到向量的字符串位置
【发布时间】:2020-10-25 15:50:09
【问题描述】:

我希望 Carnet 类中的 add 函数将一个数字添加到一个位置(位置是一个字符串),当我显示 myclass

问题是,当我在主程序中运行指令时,它显示错误(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;
}


【问题讨论】:

  • 显示位置 0 的内容,三遍。因为atoi("SDA") 为0,而atoi("FP") 为0。

标签: c++ class vector operator-overloading operators


【解决方案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 派生通常是不可取的。您应该考虑改用合成。

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

目前尚不完全清楚您打算在这里做什么。但也许向量是错误的容器?您似乎想将数字与字符串相关联。 std::map&lt;std::string, int&gt; 可以完成这项工作。

【讨论】:

  • 我可以用什么代替 atoi 程序来工作?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-08
  • 2021-11-25
  • 2021-08-29
  • 2023-03-17
  • 2020-03-08
  • 1970-01-01
相关资源
最近更新 更多