C++のvector変数

フォーラム(掲示板)ルール
フォーラム(掲示板)ルールはこちら  ※コードを貼り付ける場合は [code][/code] で囲って下さい。詳しくはこちら
栗原

C++のvector変数

#1

投稿記事 by 栗原 » 8年前

こんにちは
最近ネットで下記のようなC++ codeを見た事があります。

コード:


std::vector<int> times2(const std::vector<int>& vec) {
    std::vector<int> tmp(vec);  // copy ctor
    for (auto& x: tmp) {x *= 2;} // ←どういう意味? xは何でしょうか。 ★
    return tmp;  // copy elision
}

★の付いている行のfor文が何を実現しようとしているのでしょうか。
そのxは?

宜しくお願いします。

かずま

Re: C++のvector変数

#2

投稿記事 by かずま » 8年前

time2() をイテレータを使って書くと times2c() になります。

コード:

#include <iostream>
#include <vector>

std::vector<int> times2(const std::vector<int>& vec) {
    std::vector<int> tmp(vec);
    for (auto& x: tmp) {x *= 2;} // x は、times2c の x と同じ
    return tmp;
}

std::vector<int> times2c(const std::vector<int>& vec) {
    std::vector<int> tmp(vec);  // copy ctor
    for (auto it = tmp.begin(); it != tmp.end(); ++it) {
        auto& x = *it;  // x は、tmp[0], tmp[1], ... への参照
        x *= 2;  // time[0], time[1], ... が 全部 2倍になる
    }
    return tmp;
}

std::vector<int> times2d(const std::vector<int>& vec) {
    std::vector<int> tmp(vec);
    for (auto x: tmp) {x *= 2;}  // & がないと、times2e() の x と同じ
    return tmp;
}

std::vector<int> times2e(const std::vector<int>& vec) {
    std::vector<int> tmp(vec);  // tmp は vec のコピー
    for (auto it = tmp.begin(); it != tmp.end(); ++it) {
        auto x = *it; // x はローカル変数 (tmp[0], ... のコピー)
        x *= 2; // x を変更しても tmp[0], ... は変更されない
    }
    return tmp; // vec と同じ内容の vector を返す
}

int main()
{
    std::vector<int> a = { 1, 2, 3, 4, 5 };
    std::vector<int> b = times2(a);
    for (auto&x : b) std::cout << " " << x;
    std::cout << std::endl;

    std::vector<int> c = times2c(a);
    for (auto it = c.begin(); it != c.end(); ++it) std::cout << " " << *it;
    std::cout << std::endl;

    std::vector<int> d = times2d(a);
    for (auto i = 0; i < d.size(); ++i) std::cout << " " << d[i];
    std::cout << std::endl;
}
実行結果

コード:

 2 4 6 8 10
 2 4 6 8 10
 1 2 3 4 5

栗原

Re: C++のvector変数

#3

投稿記事 by 栗原 » 8年前

大変親切なご教授有難うございました。

C++の進化はすごいですね。
いろいろ勉強しなければ、完全に分からなくなります。

返信

“C言語何でも質問掲示板” へ戻る