Proloy
Proloy

Reputation: 363

How does std::distance() work?

I am very much new to C++11 and learning about the STL Libraries. I have written a code which is like this,

#include <bits/stdc++.h>
#include <vector>
#include <algorithm>
#include <iterator>
using namespace std;

void Print( const vector<int> &arrays )
{
   for ( int x : arrays ) cout << x << ' ';
}

int main() {
    int citys, cityPairs, fv, lv, w;
    vector <int> fvarr;
    vector <int> lvarr;
    vector <int> warr;
  vector <int> warr_temp;
  vector <int> disjoint_pairs;

    scanf("%d%d", &citys, &cityPairs);

    for(int nr = 0; nr < cityPairs; nr++){
        scanf("%d%d%d", &fv, &lv, &w);
        fvarr.push_back(fv);
        lvarr.push_back(lv);
        warr.push_back(w);
      warr_temp = warr;
    }

  for (int j = 0; j < citys; j++){
    auto result = min_element(begin(warr_temp), end(warr_temp));
    auto pos_temp = distance(begin(warr_temp), result);
    cout << pos_temp;
    auto pos = distance(begin(warr), result);
    cout << pos;
    disjoint_pairs.push_back(fvarr[pos]);
    disjoint_pairs.push_back(lvarr[pos]);
    warr_temp.erase(warr_temp.begin() + pos_temp);
  }
  // Print(disjoint_pairs);
}

What i am doing in this code is i am taking 3 vectors and 1 vector to copy the last one warr_temp = warr;. Then i am checking the minimum value in vectorwarr_temp and storing it's index in pos_temp, next i am storing that min value's index from vector warr into pos.

Now the problem is the first cout which is pos_temp giving me correct values but the second one which is pos giving me the output something like this,

-61-62-63-64

why is this happening? what are these numbers? are they pointers? I know that distance is a template so what is the right way to implement this?

If anyone can clear my doubts that would be very helpfull. Sorry if stupid question!!!

Upvotes: 1

Views: 929

Answers (1)

Rost
Rost

Reputation: 9089

The root cause of the problem is auto pos = distance(begin(warr), result); line. It gives unpredictable results because result and begin(warr) belong to different vectors.

result is iterator pointing to warr_temp element, it cannot be mixed with iterators pointing to warr elements like begin(warr).

To get element position in warr vector use std::find(begin(warr), end(warr), *result) instead:

auto warr_res = std::find(begin(warr), end(warr), *result);
auto pos = distance(begin(warr), warr_res);

Upvotes: 2

Related Questions