2016-08-20 5 views
0

私はQVector<float>を持っており、その中から最良の(最小)N値へのイテレータ/ポインタの配列を取得する必要があります。できればSTLアルゴリズムを使用して、どうすればいいですか?おそらく、これらの線に沿ってベクトル内のN個の最小値のインデックス

+1

「最高」の意味を定義してください。最大値)。 – 101010

+0

まあ、私は最小値を意味します。 –

+0

どのバージョンのQtを使用していますか? – JVApen

答えて

2

何か、:

QVector<float> data; // populated somehow 
int N; // some value <= data.size() 

std::vector<int> indices; 
int i = 0; 
std::generate_n(std::back_inserter(indices), data.size(), 
    [&i]() { return i++; }); 

std::partial_sort(indices.begin(), indices.begin() + N, indices.end(), 
    [&data](int ind1, int ind2) { return data[ind1] < data[ind2]; }); 
/* Now indices[0] through indices[N-1] contain indices 
    of the N smallest elements in data. */ 
2

希望どおりに最高のNの指数(値のみではない)のベクトルを与えるための簡単な方法があります。
Igorの答えとよく似ていますが、N個の最良インデックスを持つ結果ベクトルが得られます。

このコードは、あなたがリクエストしたのと同じように、本当にシンプルであり、STLの力を使用しています。
...

それでも
#1 => 0.29s 
#4 => 2.39s 
#0 => 3.14s 

、あなたが同じことをやってみたかったが、値は十分だろう場合は、取得することができます。

QVector<int> findBestIndices(QVector<float> &times, const int &N) 
{ 
    QVector<int> indices(times.size()); 
    std::iota(indices.begin(), indices.end(), 0); // fill with 0,1,2,... 

    std::partial_sort(indices.begin(), indices.begin()+N, indices.end(), 
        [&times](int i,int j) {return times[i]<times[j];}); 

    return QVector<int>(indices.begin(), indices.begin()+N); 
} 

int main() 
{ 
    QVector<float> times = {3.14, 0.29, 3.50, 59.38, 2.39}; 

    const int N = 3; // N best times 
    QVector<int> best = findBestIndices(times, N); 

    for(const auto &index : best) { 
     std::cout << '#' << index << " => " << times[index] << "s\n"; 
    } 

    return 0; 
} 

これが印刷されます見てくださいstd::partial_sort_copy関数を使用して、最良の要素のソートされたベクトル:

const int N = 3; 
QVector<float> best(N); 
QVector<float> times = {3.14, 0.29, 3.50, 59.38, 2.39}; 

std::partial_sort_copy(times.begin(), times.end(), best.begin(), best.end()); 

for(const auto &mytime : best) std::cout << mytime << '\n'; 
関連する問題