c++ - vector 复制不起作用,但手动 push_back 可以

标签 c++ stl

我有一个奇怪的行为,这可能是初学者的问题:

在类成员函数中,我试图用另一个 vector 替换给定的 vector 。

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;
     }
}

对应的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;
};

我很困惑。为什么复制不像 for 循环那样工作?

最佳答案

push_back调整 vector 的大小,同时写入 begin()之后的内容假设空间已经存在。你想要的看起来像这样:

std::copy(replacementPopulation.begin(),
          replacementPopulation.end  (),
          std::back_inserter(_population.getChromosomes()));

#include <iterator>得到back_inserter .

本质上,std::back_inserter是一个执行 push_back 的迭代器每次写入内容时。

关于c++ - vector 复制不起作用,但手动 push_back 可以,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27427517/

相关文章:

c++ - 我可以通过要删除的对象的回调来删除另一个拥有的对象吗?

c++ - 在另一个文件 C++ 中转发声明

C++ std::set::erase 不起作用

c++ - map 计数确实重要或只是检查存在性

c++ - STL:使用 ptr_fun 为 "const T &"类型调用 bind2nd

c++ - map::erase:按键删除和迭代器删除之间的区别?

c++ - 尝试制作对象时出错

c++ - 浮点精度在测试变量是否达到界限时的影响

c++ - 在 while 循环中使用 std::condition_variable::wait 是否正确?

c++ - 为什么 std::unordered_set 不将 CComBSTR 类型作为键?