English 中文(简体)
指定不同大小的 std:: 数组
原标题:Assigning different sized std::array

我有一个人口密集的台阶: 拥有有意义的数据和一个台阶的阵列:: 带0s的阵列。 我希望将 6 的阵列分配到 8 的阵列 。 在 c++ 中, 使用什么方式来做?

最佳回答

如果目标数组大于源数组, 您可以使用 std:: copy :

std::array<int, 6> arr1;
std::array<int, 10> arr2;
// Fill arr1...
std::copy(arr1.begin(), arr1.end(), arr2.begin());

如果目的地数组较短, 那么您就必须复制到某个点。 我的意思是, 您仍然可以使用 < code>std:: opy 来做到这一点, 但是您必须做一些类似的事情 :

std::array<int, 10> arr1;
std::array<int, 6> arr2;
// Fill arr1...
std::copy(arr1.data(), arr1.data() + arr2.size(), arr2.begin());

这对两种情况都有效:

std::copy(arr1.data(), arr1.data() + std::min(arr1.size(), arr2.size()), arr2.begin());
问题回答

不清楚你究竟在问什么,所以这个答案包括了几种可能性:

#include <array>
#include <algorithm>

int main() {
  // Uninitialized std::array
  std::array<int, 1> arr1;

  std::array<int, 2> arr2 = {0,1};

  // Not legal, sizes don t match:
  // std::array<int, 3> arr3 = arr2;

  // Instead you can do:
  std::array<int, 3> arr3;
  std::copy(arr2.begin(), arr2.end(), arr3.begin());

  // If the sizes match and the types are assignable then you can do:
  std::array<int, 3> arr4 = arr3;

  // You can also copy from the bigger to the smaller if you re careful
  std::copy_n(arr3.begin(), arr1.size(), arr1.begin());
}




相关问题
Undefined reference

I m getting this linker error. I know a way around it, but it s bugging me because another part of the project s linking fine and it s designed almost identically. First, I have namespace LCD. Then I ...

C++ Equivalent of Tidy

Is there an equivalent to tidy for HTML code for C++? I have searched on the internet, but I find nothing but C++ wrappers for tidy, etc... I think the keyword tidy is what has me hung up. I am ...

Template Classes in C++ ... a required skill set?

I m new to C++ and am wondering how much time I should invest in learning how to implement template classes. Are they widely used in industry, or is this something I should move through quickly?

Print possible strings created from a Number

Given a 10 digit Telephone Number, we have to print all possible strings created from that. The mapping of the numbers is the one as exactly on a phone s keypad. i.e. for 1,0-> No Letter for 2->...

typedef ing STL wstring

Why is it when i do the following i get errors when relating to with wchar_t? namespace Foo { typedef std::wstring String; } Now i declare all my strings as Foo::String through out the program, ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

Window iconification status via Xlib

Is it possible to check with the means of pure X11/Xlib only whether the given window is iconified/minimized, and, if it is, how?

热门标签