【问题标题】:Segmentation Fault container分段故障容器
【发布时间】:2021-02-24 06:04:42
【问题描述】:
#include <map>
#include <vector>
#include <string>
#include <sstream>
#include <iostream>

using namespace std;

int size;

typedef vector<string> list;
typedef map<string, list> table;

void display(table &t){
  cout << "\t\tCar Model\t\tTotal sold unit\t\t Cost of each unit\n"<<endl;
  for(int i=0; i < size; i++){
   cout << i << "\t\t" << t["Car_Model"][i]
             << "\t\t" << (t["num"][i] + t["num_"][i])
             << "\t\t" << t["Cost"][i]
             << "\n";
  }
}

int main(){
  cout<<"Enter number of Car Models: "<<endl;
  cin>>size;
  table t;
  t["Car_Model"].reserve(size);
        for(int i = 0; i < size; i++){
            cout<<"Enter Car Model: ";
            cin>>t["Car_Model"][i];
            cout<<"Cost: ";
            cin>>t["Cost"][i];
            cout<<"No. of unit sold(2000-2010): ";
            cin>>t["num"][i];
            cout<<"No. of unit sold(2010-2020): ";
            cin>>t["num_"][i];
        }    
        display(t);
}

这是我的代码。它在编译时没有任何错误。但是在运行时,当我存储数据时,它会给出分段错误的错误。 当程序尝试访问不允许访问的内存位置,或尝试以不允许的方式访问内存位置(例如,尝试写入只读位置,或覆盖部分操作系统)。

【问题讨论】:

  • 我强烈反对将您自己的类型命名为与现有标准类型相同,尤其是在使用using namespace std; 时。它可能会在不例外的时刻咬你一口。

标签: c++ dictionary stl


【解决方案1】:

常见错误,reserve 不改变向量的大小,你想要resize。像这样

t["Car_Model"].resize(size);

reserve 为向量分配空间而不改变它的大小。其目的是在使用push_back 或类似方法时防止昂贵的向量重新分配。但在这种情况下,由于您知道所需矢量的大小,您应该只使用resize 来获得该大小。

PS,typedef list 不是一个好主意。 C++ 已经有一个 std::list 类型,所以使用 typedef 给您的程序提供另一种称为 list 的类型非常令人困惑。

【讨论】:

    猜你喜欢
    • 2018-01-19
    • 1970-01-01
    • 2016-09-09
    相关资源
    最近更新 更多