88#include < unordered_set>
99#include < vector>
1010#include < omp.h>
11+ #include < cmath>
12+ #include < limits>
1113using namespace std ;
1214
1315vector<int > HNSWGraph::searchLayer (Item& q, int entry_point, int ef, int lc) {
16+ if (lc < 0 || lc >= layerEdgeLists.size ()) {
17+ cerr << " Error: Invalid layer index." << endl;
18+ exit (EXIT_FAILURE);
19+ }
1420 set<pair<double , int >> candidates;
1521 set<pair<double , int >> nearestNeighbors;
1622 unordered_set<int > isVisited;
@@ -49,7 +55,18 @@ vector<int> HNSWGraph::searchLayer(Item& q, int entry_point, int ef, int lc) {
4955 return results;
5056}
5157
52- vector<int > HNSWGraph::KNNSearch (Item& q, int K) {
58+ vector<int > HNSWGraph::KNNSearch (Item& q, int K, int N) {
59+
60+ if (K <= 0 || std::ceil (K) != K || K > std::numeric_limits<int >::max ()) {
61+ cerr << " Error: Invalid value of K for KNNSearch." << endl;
62+ exit (EXIT_FAILURE);
63+ }
64+
65+ if (K > N) {
66+ std::cerr << " Error: Value of K (" << K << " ) is greater than the number of data points (N = " << N << " )." << std::endl;
67+ exit (EXIT_FAILURE);
68+ }
69+
5370 int maxLyer = layerEdgeLists.size () - 1 ;
5471 int entry_point = enterNode;
5572 for (int l = maxLyer; l >= 1 ; l--) {
@@ -59,6 +76,10 @@ vector<int> HNSWGraph::KNNSearch(Item& q, int K) {
5976}
6077
6178void HNSWGraph::addEdge (int st, int ed, int lc) {
79+ if (lc < 0 || lc >= layerEdgeLists.size ()) {
80+ cerr << " Error: Invalid layer index." << endl;
81+ return ;
82+ }
6283 if (st == ed) {
6384 return ;
6485 }
@@ -91,10 +112,12 @@ void HNSWGraph::Insert(Item& q) {
91112 int MM = l == 0 ? MMax0 : MMax;
92113 vector<int > neighbors = searchLayer (q, entry_point, efConstruction, i);
93114 vector<int > selectedNeighbors = vector<int >(neighbors.begin (), neighbors.begin ()+min (int (neighbors.size ()), M));
94- for (int n: selectedNeighbors) {
95- addEdge (n, nid, i);
96- }
97- for (int n: selectedNeighbors) {
115+ for (size_t j = 0 ; j < selectedNeighbors.size (); j++) {
116+ int n = selectedNeighbors[j];
117+ addEdge (n, nid, i);
118+ }
119+ for (size_t j = 0 ; j < selectedNeighbors.size (); j++) {
120+ int n = selectedNeighbors[j];
98121 if (layerEdgeLists[i][n].size () > MM) {
99122 vector<pair<double , int >> distPairs;
100123 for (int nn: layerEdgeLists[i][n]) {
0 commit comments