为什么存储此向量时会出现分段错误

why is there a Segmentation Fault with the storing of this vector?

本文关键字:分段 错误 存储 向量 为什么      更新时间:2023-10-16

我在看似精细的代码中有一个分段错误。我知道故障发生在哪里,但似乎无法修复它。

for(int i=0; i<position.size();i++)
    {
            ordered[position[i]-1]= name[i];
      }

这是它的缺点所在该代码应该读取具有相应数字的名称文件,然后按其编号顺序对名称进行排序。以下是供参考的完整代码:

#include<iostream>
#include<string>
#include<vector> 
#include<fstream>
#include<sstream>
#include<algorithm>
using namespace std;
void print_vector(vector<string> ordered){
    for(int i = 0; i < ordered.size(); i++)
            cout << ordered[i] << " ";
    cout << endl;
}
int main() 
{
    ifstream inf;
    inf.open("input2.txt");
    string s;
    string word;
    vector<int> position;
    vector<string> name;
    vector<string> ordered;
    string n;
    int p;
    while( !inf.eof())
    {
            getline(inf, s);
            istringstream instr(s);
            instr>>p;
            instr>>n;
            while(!instr.eof()){
                    position.push_back(p);
                    name.push_back(n);
                    instr>>p;
                    instr>>n;
            }
    }
    for(int i=0; i<position.size();i++)
    {
            ordered[position[i]-1]= name[i];

    }
    print_vector(ordered);
    inf.close();
    return 0;
}

在不编译和测试我的答案的情况下,我认为为了正确使用赋值和向量"有序",您必须确保0 <= position[i]-1 < ordered.size()始终如此。由于"已订购"开始时为空,因此您正在尝试越界访问。请参阅此问题/答案。

因此,您可能需要考虑使用另一个修饰符成员函数(如"insert"或"push_back")以避免越界问题。虽然,与此同时,您可能希望更改存储数据的方式,因为您试图依靠"有序"向量的索引值来表示某个整数键/值。