4

ベクターデータを以下のようにコピーしようとしsampleYいます

std::map<std::string, std::vector<double > >sample;
std::map<std::string, std::vector<double > >::iterator it1=sample.begin(), end1=sample.end();
std::vector<double> Y; 

次のコードを使用しています:

 while (it1 != end1) {
  std::copy(it1->second.begin(), it1->second.end(), std::ostream_iterator<double>(std::cout, " "));
++it1;
}

出力は正常に出力されますが、上記の std::copy ブロックを以下に置き換えると、segfault が発生します。

 while (it1 != end1) {
std::copy(it1->second.begin(), it1->second.end(), Y.end());
++it1;
}

it1->second の内容を Y にコピーしたいだけです。なぜ機能しないのですか?どうすれば修正できますか?

4

2 に答える 2

16

ベクトルにオブジェクトを挿入したいのは明らかです。ただし、std::copy()渡されたイテレータを取得して書き込むだけです。begin()およびイテレータによって取得されるend()イテレータは挿入を行いません。使用したいものは次のようなものです:

std::copy(it1->second.begin(), it1->second.end(), std::back_inserter(Y));

std::back_inserter()関数テンプレートは、push_back()引数を使用してオブジェクトを追加する反復子のファクトリ関数です。

于 2012-04-30T02:45:28.030 に答える
2
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;


int main() {
    // your code goes here
    vector<int> vec;
    vector<int> test;
    vec.push_back(1);
    //test.push_back(0);
    copy(vec.begin(),vec.begin()+1,test.begin());
    cout << *(test.begin());
    return 0;
}

出力: 実行時エラー時間: 0 メモリ: 3424 信号:11

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

using namespace std;


int main() {
    // your code goes here
    vector<int> vec;
    vector<int> test;
    vec.push_back(1);
    test.push_back(0);
    copy(vec.begin(),vec.begin()+1,test.begin());
    cout << *(test.begin());
    return 0;
}

出力: *成功時間: 0 メモリ: 3428 信号:0 *

1

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

using namespace std;


int main() {
    // your code goes here
    vector<int> vec;
    vector<int> test(5);
    vec.push_back(1);
    //test.push_back(0);
    copy(vec.begin(),vec.begin()+1,test.begin());
    cout << *(test.begin());
    return 0;
}

成功時間: 0 メモリ: 3428 信号: 0

1

その理由は、ベクトルを初期化していないためです。vector.begin() は制限された場所を指しています! back_inserter(vector) を使用すると、*(deference) 操作ではなく vector.push_back を内部的に使用する back_insert_interator が返されます。したがって、back_inserter が機能します。

于 2014-03-28T03:17:25.820 に答える