为什么存储此向量时会出现分段错误
why is there a Segmentation Fault with the storing of this vector?
我在看似精细的代码中有一个分段错误。我知道故障发生在哪里,但似乎无法修复它。
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")以避免越界问题。虽然,与此同时,您可能希望更改存储数据的方式,因为您试图依靠"有序"向量的索引值来表示某个整数键/值。
相关文章:
- 在某些循环内使用vector.push_back时出现分段错误
- 为什么在运行时没有向我们提供有关分段错误的更多信息?
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 当我的阵列太大时出现分段错误
- 分段错误当我试图运行程序时出错
- 在c++中初始化矩阵时出现分段错误(核心转储)
- 尝试使用集合函数时出现分段错误
- 我无法缩小此分段错误的原因
- g++的分段错误(在NaN上使用to_string两次时)
- 我是如何在这段代码中出现分段错误的
- 创建结构的数组时遇到分段错误
- 在c++中键入向量中的所有值后,得到分段错误(核心转储)
- 在 c++ 中实现 Trie 时出现分段错误
- 为什么 fstream 在打开带有格式的文件时会导致分段错误?
- 为什么我遇到分段错误?
- 动态类的分段错误(家庭作业问题)
- 分段错误 - 读取初始化指针的数组
- 如何摆脱C ++中的分段错误错误?
- 使用 CTYPE 时出现分段错误
- 为什么代码给出分段错误?