将矢量内容复制到数组练习中



我目前正在阅读C++入门第 5 版。在第 3 章练习 3.42 中,我被要求"编写一个程序来将 int 的向量复制到 int 数组中"。

下面的代码有效。但是我有几个问题。

1) 在第 16 行,

int arr[5]; 

初始化包含 5 个元素的数组。如何更改数组,使其自动获得/具有与矢量 ivec 相同的大小?

2)有没有更简单的方法可以用本书到目前为止所教的内容编写程序?

//Exercise 3.42
#include "stdafx.h"
#include <iostream>
#include <vector>
using std::vector;
using std::begin;
using std::endl;
using std::cout;
using std::end;
int main(){
vector<int> ivec = { 1, 2, 3, 4, 5 }; //initializes vector ivec.
int arr[5]; //initializes array "arr" with 5 null elements.
int i1 = 0; // initializes an int named i1.
for (vector<int>::iterator i2 = ivec.begin(); i2 != ivec.end(); ++i2){ 
    arr[i1] = *i2; //assigned the elements in ivec into arr.
    ++i1; // iterates to the next element in arr.
}
for (int r1 : arr){ //range for to print out all elements in arr.
    cout << r1 << " ";
}
cout << endl;
system("pause");
return 0;
}

1)你不能在可移植C++中使用数组:数组长度在编译时是固定的。但是你可以用一个矢量

2)当然,假设目标数组足够大,请使用std::copy

std::copy(std::begin(ivec), std::end(ivec), arr);

还要删除所有这些using,它们只不过是噪音。一点点清洁给:

#include <iostream>
#include <algorithm>
#include <vector>
int main(){
  std::vector<int> ivec = { 1, 2, 3, 4, 5 };
  int arr[5];
  std::copy(std::begin(ivec), std::end(ivec), arr);
  for (auto r1 : arr){
    std::cout << r1 << ' ';
  }
  std::cout << std::endl;
}

您甚至可以重复使用std::copy来打印矢量的内容:

int main(){
  std::vector<int> ivec = { 1, 2, 3, 4, 5 }; //initializes vector ivec.
  int arr[5]; //initializes array "arr" with 5 null elements.
  std::copy(std::begin(ivec), std::end(ivec), arr);
  std::copy(arr, arr + 5, std::ostream_iterator<int>(std::cout, " "));
}

现场演示


注意:

如果你想为副本保留一个手写循环,一个更规范的/c ++ 11方法是:

auto i1 = std::begin(arr);
auto i2 = std::begin(ivec);
while ( i2 != std::end(ivec)){ 
    *i1++ = *i2++;
}

1)如果你需要一个长度在编译时未知的数组,你可以在堆上动态创建数组(在实际代码中,你通常应该使用std::vector):

int* arr=new int[ivec.size()]; 

但是,这还有其他一些缺点。 例如,开始(arr)/结束(arr),因此循环的范围不再起作用,您必须在某个时候手动删除数组(我不知道您是否已经了解了 RAII 和智能指针)

2)Quantdev已经为这部分提供了非常好的答案

最新更新