我對C++ 11非常陌生,對STL庫有所瞭解。我已經寫了代碼是這樣的,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);
}
我在此代碼做什麼是我以3個載體和1個向量的最後一個warr_temp = warr;
複製。然後我檢查矢量warr_temp
中的最小值並將其索引存儲在pos_temp
中,接下來我將該最小值的索引從矢量warr
存儲到pos
。
現在的問題是第一cout
這是pos_temp
給我正確的價值觀,但第二個是pos
給我的輸出這樣的事情,
-61-62-63-64
爲什麼會出現這種情況?這些數字是什麼?他們是指針嗎?我知道距離是一個模板,那麼實現這個的正確方法是什麼?
如果有人可以清除我的疑惑,這將是非常有益的。 對不起,如果愚蠢的問題!
嗨羅斯特,我用自己的方式它給我這樣的錯誤'敵不過「運算符<<」」,「上這一行「cout << pos;」 。但是,如果我打印它像這樣「cout << * pos」那麼它給我的數字是在這些指標,但不是指數。 – Proloy
@Proloy查看更新的答案。 'std :: find'也給你迭代器,你應該使用'std :: distance'來獲得索引。 – Rost
非常感謝您解決此問題! – Proloy