4

私は持っていますstd::vector<std::pair<int,double>>、コードの長さと速度の点で取得するための簡単な方法はありますか?

  • std::vector<double>2番目の要素のa
  • std::vector<double>::const_iterator新しいベクトルを作成せずに2番目の要素に

質問を入力するときに強調表示された質問のリストで、同様の質問を見つけることができませんでした。

4

4 に答える 4

6

最初の質問では、transform を使用できます (以下の例では c++11 のラムダを使用)。2 番目の質問については、それはできないと思います。

#include <vector>
#include <string>
#include <algorithm>
#include <iostream>

int main(int, char**) {

    std::vector<std::pair<int,double>> a;

    a.push_back(std::make_pair(1,3.14));
    a.push_back(std::make_pair(2, 2.718));

    std::vector<double> b(a.size());
    std::transform(a.begin(), a.end(), b.begin(), [](std::pair<int, double> p){return p.second;});
    for(double d : b)
        std::cout << d << std::endl;
    return 0;
}
于 2012-09-06T11:11:22.063 に答える
6

あなたが望むのは次のようなものだと思います:

std::vector<std::pair<int,double>> a;

auto a_it = a | boost::adaptors::transformed([](const std::pair<int, double>& p){return p.second;});

コンテナーのコピーを作成せずに、コンテナーに対して変換イテレーターを作成します (double を反復処理します)。

于 2012-09-06T11:13:38.573 に答える
1

現時点で私が考えることができる最も単純なものは次のようなものです:

std::vector<std::pair<int, double>> foo{ { 1, 0.1 }, { 2, 1.2 }, { 3, 2.3 } };

std::vector<double> bar;
for (auto p : foo)
    bar.emplace_back(p.second);
于 2012-09-06T11:13:03.560 に答える
0

私のやり方 :

std::pair<int,double> p;
std::vector<std::pair<int,double>> vv;  
std::vector<std::pair<int,double>>::iterator ivv;

for (int count=1; count < 10; count++)
{
    p.first = count;
    p.second = 2.34 * count;
    vv.push_back(p);
}

ivv = vv.begin();
for ( ; ivv != vv.end(); ivv++)
{
    printf ( "first : %d  second : %f", (*ivv).first, (*ivv).second );
}
于 2012-09-06T11:21:33.933 に答える