c++ - Segmentation fault in a nested loop for doing calculations using each 2 elements in vector -


i have time consuming function, needs calculation using each 2 elements in std::vector. way doing is,

std::vector<int> vec; (auto = vec.begin(); != vec.end(); ++ it)   (auto it2 = vec.begin(); it2 != vec.end(); ++ it2)     if (it2 != it)       f(*it, *it2) // function 

i wondering if there other better ways this, because process cost time.

besides, have tried use openmp parallelize outer loop, works fine when use std::vector, if similar things std::map, returns segmentation fault.


updates parallel loop.

the thing doing calculate music similarity using music tags. tags of each music in std::map called map_tag, , song ids in vector called song_vec. did not use iterator here, major part of code below. seems problems happen when reading data map_tag, because if remove part parallel loop works fine.

unsigned int finishcount = 0; std::map<std::string, std::vector<std::string>> map_tag;  #pragma omp parallel shared(finishcount) num_threads(2) {     #pragma omp     (std::size_t = 0; < numofdoc; ++ i) // numofdoc number of music     {         std::string song_id = song_vec[i];         std::vector<std::string> song_tag;         song_tag = map_tag[song_id]; // problems here          (std::size_t j = 0; j < numofdoc; ++ j)         {             std::string song_id2 = song_vec[j];             std::vector<std::string> song_tag2;             song_tag2 = map_tag[song_id2]; // problems here              if (song_id != song_id2)                  calsimilarity(song_tag, song_tag2);         }          // somethings here          #pragma omp critical // use show progress         {             finishcount ++;             cout << finishcount << "\r";             cout.flush();         }     } } 

another update, have add #pragma omp critical before problem part, , program can work correctly. not understand how fault caused, because map_tag read variable, can not modified inside loop.

i new c++, of kindly help.

first of all, change this:

std::vector<int> vec; (auto = vec.begin(); != vec.end(); ++ it)   (auto it2 = vec.begin(); it2 != vec.end(); ++ it2)     if (it2 != it)       f(*it, *it2) // function 

to this:

std::vector<int> vec;  /// fill vec here... :(  (auto = vec.begin(); != vec.end(); ++ it)   (auto it2 = next(it); it2 != vec.end(); ++ it2) /// see initial it2 value       f(*it, *it2) // function 

and you've reduced iterations more half.

you're doing lot of duplicate work. each inner loop calls f() vec.size()-1 times.

start there, see takes you. also, nothing in question openmp specific, , can't tell parallelization happening. please update more code or detail.


Comments

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -