有人可以告诉我为什么在Visual Studio中编译并运行正常,但在编译GNU C ++编译器时出现分段错误会失败
不能为我的生活搞清楚这一点。我检查了前缀/后缀运算符,并确保迭代器在条件语句中正确放置...我错过了什么?通常我在处理分配/解除分配动态数组时遇到这个问题,我在这里没有这样做。
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <random>
#include <unordered_set>
namespace std{
template <>
struct hash<vector<int>> : public unary_function<vector<int>, size_t>
{
size_t operator()(const vector<int>& v) const
{
return v.size();
}
};
}
using namespace std;
struct testCase{
int n;
int m;
vector <int> wordVector;
};
bool lexOrderConfirm(std::vector<int>::const_iterator, std::vector<int>::const_iterator, std::vector<int>::const_iterator, int );
int main() {
int t;
cin>>t;
vector <testCase*> testCaseVector(t);
for (int i = 0; i < t; ++i){
testCaseVector[i] = new testCase;
cin>>testCaseVector[i]->n;
cin>>testCaseVector[i]->m;
}
for (int i = 0; i < t; ++i){
std::unordered_set<std::vector<int>, std::hash<std::vector<int> > >permutations;
int permu = pow((double)testCaseVector[i]->n, testCaseVector[i]->m);
int count = 0;
for (int z= 0; z < (permu*10); ++z){
std::random_device rd;
std::default_random_engine randomeng( rd() );
int v;
for (int b = 0; b < testCaseVector[i]->m; ++b){
v= randomeng() % testCaseVector[i]->n + 1; /*random number between 1 and n*/
testCaseVector[i]->wordVector.push_back(v);
}
std::sort(testCaseVector[i]->wordVector.begin(), testCaseVector[i]->wordVector.end());
permutations.insert(testCaseVector[i]->wordVector);
testCaseVector[i]->wordVector.clear();
}
do {
vector <int> test = *permutations.begin();
do {
std::vector<int>::const_iterator start = test.begin();
std::vector<int>::const_iterator end;
end = test.end();
std::vector<int>::const_iterator lastElem = start+(testCaseVector[i]->m-1);
if (lexOrderConfirm(start, end, lastElem, testCaseVector[i]->n)){
++count;
}
}while(std::next_permutation(test.begin(),test.end()));
permutations.erase(permutations.begin());
test.clear();
}while(!permutations.empty());
count = count%100000007;
cout<<count<<endl;
}
return 0;
}
bool lexOrderConfirm(std::vector<int>::const_iterator start, std::vector<int>::const_iterator end, std::vector<int>::const_iterator lastElem, int N){
bool confirmed = true;
for (std::vector<int>::const_iterator t = start; t != end; ++t){
if ((2* (*t) > N)){
} else if ((2*(*t) <= N) && (*(t+1) >= 2 * (*t)) && (t != (lastElem))){
}else{
confirmed = false;
break;
}
}
return confirmed;
}
答案 0 :(得分:1)
原因是,当然,您正在取消引用一些未初始化的指针。从您当前的代码中无法分辨,因为一方面它取决于用户输入。 t = 2
对我来说似乎运行得很好;即使我不确定它是否按预期工作。
但为什么它在Visual Studio上运行?
因为VC++
没有将指针初始化为NULL。它正在起作用,因为未初始化的指针在某种程度上像初始化指针一样工作。所以基本上是未定义的行为。
为什么在编译GNU C ++编译器时出现分段错误会失败?
因为g++
将指针初始化为NULL