mercredi 28 septembre 2022

C++ Simplify loop over map and extending/overwriting of vector

Given

  • std::vector<int> vec1 of size s_vec and capacity c.
  • std::vector<int> vec2.
  • std::map<int, int> m of size s_m >= s_vec.
  • std::unordered_set<int> flags.
  • bool flag = False

I want to copy as many values of m (in order) into vec1 (overwriting previous values) without exceeding the capacity c. If any values remain I want to push those values to the end of vec2. For each of these, values I want to check if they are in flags. If they are, I'd like to set flag to true.

This is how I currently, achieve this:

  int i = 0;
  for (auto const& e : m) {
    if(i < c) {
      if(i == vec1.size()) {
        vec1.push_back(e.second);
      } else {
        vec1.at(i) = e.second;
      }
    } else {
      vec2.push_back(e.second);
      if(flags.count(e.second)){
        flag = true;
      }
    }
  }

I am new to C++ coming from python and R. Therefore, I assume that this can be simplified quite a bit (with iterators?). What can I do to improve the code here?

Aucun commentaire:

Enregistrer un commentaire