【问题标题】:C++ Vectors Segmentation FaultC++ 向量分段错误
【发布时间】:2017-09-14 20:34:35
【问题描述】:

我正在开发一个具有输入文件的程序,它可以添加、删除或打印字符串。我的print 函数正在工作,但是当我取消注释显示的代码行时出现分段错误。

int main()
{
    vector <string> vec; //Creates an empty vector
    string command;
    string word;
    int index;

    ifstream fin;
    fin.open("datalabvec.dat"); //Opens the input file

    if (!fin)
        cout << "The input file does not exist" << endl << endl;
    else
    {
        fin >> command;

        while (fin)
        {
            if (command =="Add")
            {
                fin >> word >> index;
                //addVec (vec, word, index);
            }
            //if (command == "Remove")
            //{
                //fin >> index;
                //remVec (vec, index);
            //}
            // else //Print function
            {
                printVec(vec);
            }
            fin >> command;
        }
    }
}

void addVec(vector <string> &v, string word, int ind)
{
    int size = v.size();
    if (ind > size + 1)
        cout << "Invalid adding at index " << ind << endl;
    else
    {
        v.insert(v.begin()+ind, word);
    }
}

void remVec(vector <string> &v, int ind)
{
    int size = v.size();
    if (ind > size)
        cout << "Invalid removing at index " << ind << endl;
    else
    {
        v.erase(v.begin() + ind);
    }
}

void printVec(const vector <string> v)
{
    int size = v.size();

    for (int i = 0; i < size; i++)
    {
        cout << v[i] << "\t";
    }
    cout << endl;
}

输入文件

Remove      0
Add Student 0
Add Kid     0
Add Final   1
Add Grow    1
Add Note    2
Add Bad     6
Remove      5
Add Worse   -1
Print
Add Rich    5
Remove      1
Remove      7
Add Mind    2
Remove      3
Print

【问题讨论】:

  • 您提到了注释代码,但您的示例中没有任何 cmets...实际上,您的打印功能也丢失了。
  • 那是因为您的两个函数都允许 UB 用于某些输入。修正你的比较。
  • 有问题吗?

标签: c++ vector segmentation-fault


【解决方案1】:

在您的添加功能中。我猜你错误地在 if 语句中写了 size+1 。它应该是 size-1,因为 vector 的最后一个成员是 size-1。 [0] - [size-1]。正确的语句是 if(ind >= size) 或 ind > size-1。就像你在 writer 函数中使用 for 循环一样。

正如布拉德在下面的评论中所建议的那样。检查天气 ind >= 0 是个好主意。

void addVec (vector <string> &v, string word, int ind)
{
  int size = v.size();
  if (ind < 0 || ind >= size)
    cout << "Invalid adding at index " << ind << endl;
  else
    {
      v.insert(v.begin()+ind, word);
    }
}

void remVec (vector <string> &v, int ind)
{
  int size = v.size();
  if (ind < 0 || ind >= size)
    cout << "Invalid removing at index " << ind << endl;
  else
    {
      v.erase(v.begin() + ind);
    }
}

【讨论】:

  • 显然,还必须将索引与零进行比较。
  • 索引不能为0?
猜你喜欢
  • 2019-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-16
  • 1970-01-01
  • 1970-01-01
  • 2020-04-19
  • 1970-01-01
相关资源
最近更新 更多