我想教自己C++。要做到這一點,我爲自己寫了一個主要的發現應用程序,這是一個挑戰。我用一種效率較低的算法成功了一次python(學習python)。我正在使用雙向鏈表來存儲素數。目前我只是試圖在一個線程中運行它,但是我將它加倍連接,以便稍後可以多線程處理。鏈接列表值的問題C++
無論如何,TL; DR調試器顯示程序卡住試圖分配一個值給Prime構造函數中的開始鏈接的prm int我已經做了一堆搜索,但我無法弄清楚我是什麼,做錯了。 (還要注意bings是調試消息)
#include <iostream>
#include <math.h>
#include <cmath>
using namespace std;
using std::cout;
struct PLink{
int prm;
PLink *next;
PLink *prev;
};
class Prime{
public:
PLink *start, *end;
Prime(){
start -> prm = 2;
end -> prm = 3;
start->next = end;
end->next = NULL;
start->prev = NULL;
end->prev = start;
addToEnd(5);
cout <<"cbing" << endl;
}
void insert(int val){
}
void addToEnd(int val){//adds a new prime to the end of the list
PLink *tmp = new PLink;
tmp->prm = val;
tmp->prev = end;
end->next = tmp;
tmp->next = NULL;
tmp = end;
cout << tmp->prm << endl;
cout << "addbing" << endl;
}
bool comp(int pot){ //compares the potential prime against known primes via modulo
int lim = sqrt(pot);
PLink * current = start;
bool check = false;
cout<<"bing " << pot << endl;
while (current->prm < lim && check == false){
if (pot%current->prm == 0) {
check = true;}
current = current->next;
}
return check; //false means its prime true means its not
}
};
int main()
{
Prime primeList;
int cap = 10000;
int beg = 5;
int count = 3;
bool toggle = false;
bool check = false;
cout << "2 \n3 \n5" << endl;
while(count < cap){
beg += 2;
cout << "bing" << endl;
if (toggle){
beg += 2;}
toggle = !toggle;
check = primeList.comp(beg);
if (check == false){
primeList.addToEnd(beg);
count++;
cout << "bing2" << endl;
}
}
};
爲什麼不只是使用STL'std :: list',然後你就可以繼續你的程序試圖做的事 - 找到素數。 – PaulMcKenzie
'start - > prm = 2;結束 - > prm = 3; start-> next = end;'你在構造函數中訪問一個未初始化的指針。這不起作用。 – PaulMcKenzie
如果您必須編寫自己的鏈接列表,請不要將其與主要搜索者結合。你最終必須同時調試兩種算法。不好玩。 – user4581301