c++ - 为什么存储此 vector 会出现段错误?

标签 c++ vector segmentation-fault

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

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

最佳答案

在不编译和测试我的答案的情况下,我认为为了正确使用 vector “有序”赋值,你必须确保 0 <= position[i]-1 < ordered.size()总是这样。因为“已订购”一开始是空的,所以您正试图越界访问。参见 this question/ answer .

因此,您可能要考虑使用另一个修饰符成员函数,例如 'insert' 或 'push_back' 来避免越界问题。尽管与此同时,您可能想要更改存储数据的方式,因为您正试图依赖“有序” vector 的索引值来表示一些整数键/值。

关于c++ - 为什么存储此 vector 会出现段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19802988/

相关文章:

c++ - 如何检查传递给函数的容器是否已排序,如果没有则对其进行排序

c++ - 处理包含动态分配成员的对象的 vector

c++ - TCP Socket block 函数段错误,由移动 if 语句引起

c++ - 重载运算符%

c++ - 将 0x1234 转换为 0x11223344

c++ - OpenPose:E0312/没有从 “fLS::clstring”到 “const op::String”的适当的用户定义转换以及其他错误

c++ - 指向可能存在或不存在的对象的指针 vector

c++ - QT--OpenMP运行时错误SIGSEGV

c - Malloc 语句给出段错误 11

c++ - 如何估计相机从场景中拍摄优质图像的曝光时间