我有一个奇怪的行为,这可能是一个初学者的问题:
在类成员函数中,我试图用另一个向量替换给定的向量.
template <typename FITNESS_TYPE>
void BaseManager<FITNESS_TYPE>::replacePopulation (
typename Population<FITNESS_TYPE>::chromosome_container replacementPopulation)
{
_population.getChromosomes().clear();
//This inserts the contents of replacementPopulation into _population.getChromosomes()
for (
typename Population<FITNESS_TYPE>::chromosome_container::iterator
it = replacementPopulation.begin();
it != replacementPopulation.end();
++it)
{
_population.getChromosomes().push_back(*it);
}
//But this does nothing...
std::copy(replacementPopulation.begin(),replacementPopulation.end(), _population.getChromosomes().begin());
for (typename Population<FITNESS_TYPE>::chromosome_container::iterator it = _population.getChromosomes().begin(); it!=_population.getChromosomes().end(); ++it)
{
std::cout << "CHROM: " << **it << std::endl;
}
}
Run Code Online (Sandbox Code Playgroud)
相应的getChromosomes()getter如下:
template <typename FITNESS_TYPE>
class Population : public printable {
public:
typedef typename std::vector<Chromosome::BaseChromosome<FITNESS_TYPE>* > chromosome_container;
typedef typename chromosome_container::const_iterator const_it;
typedef typename chromosome_container::iterator it;
const chromosome_container& getChromosomes() const { return _chromosomes; }
chromosome_container& getChromosomes() { return _chromosomes; }
private:
chromosome_container _chromosomes;
};
Run Code Online (Sandbox Code Playgroud)
我糊涂了.为什么副本不像for循环那样工作?
push_back调整向量的大小,而写入begin()和后面的内容假定空间已经存在.你想要的是这样的:
std::copy(replacementPopulation.begin(),
replacementPopulation.end (),
std::back_inserter(_population.getChromosomes()));
Run Code Online (Sandbox Code Playgroud)
#include <iterator>得到back_inserter.
从本质上讲,std::back_inserter是一个迭代器,push_back每当有东西写入它时就会执行.
| 归档时间: |
|
| 查看次数: |
201 次 |
| 最近记录: |