私はC++ 11で非常に新しく、STLライブラリについて学んでいます。私は私が最後の1 warr_temp = warr;
をコピーする3つのベクトルと1つのベクトルを取っている私は、このコードでやっている何を、このようなコード、std :: distance()はどのように機能しますか?
#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);
}
をされて書かれています。次に、ベクトルwarr_temp
の最小値をチェックし、インデックスをpos_temp
に格納しています。次に、ベクトルwarr
からその最小値のインデックスをpos
に格納しています。
さて問題はpos_temp
は私に正しい値が、pos
私にこのような出力に何かを与えている秒1を与えている最初のcout
で、
-61-62-63-64
なぜこの出来事はありますか?これらの数字は何ですか?彼らはポインタですか?距離はテンプレートなので、これを実装する正しい方法は何ですか?
誰かが私の疑義を解消できれば、非常に役に立ちます。 申し訳ありません愚かな質問!!!
こんにちはロストを、私はそれが "「<<演算子「の一致「」」私は、このようなエラーを与えていないあなたの方法を使用していますこの行 "cout << pos;" 。しかし、もし私がこのような "cout << * pos"のように印刷すると、インデックスにはあるがインデックスにはない番号が与えられます。 – Proloy
@Proloy更新された回答を参照してください。 'std :: find'はイテレータも提供します。インデックスを取得するために' std :: distance'を適用しなければなりません。 – Rost
これを修正してくれてありがとう! – Proloy