關于如何將標準 c 陣列復制到另一個陣列中,它是眾所周知的:
char test[20] = "asdasd";
char test2[19] = "asdassdsdfd";
strcpy_s(test, sizeof(test), test2);
但是我怎么能用 a 做同樣的事情std::array呢?(最好沒有 for 回圈)
std::array<char, 20> test = {"asdasd"};
std::array<char, 19> test2 = {"asdassdsdfd"};
// copy test2 into test
uj5u.com熱心網友回復:
有很多方法。你可以使用strcpy_s(test.data(), sizeof(test), test2.data()),但我不會推薦它。基本相同的更通用的版本是std::copy(test.begin(), test.size(), test2.begin());即使std::arrays 中的型別發生變化也將繼續正確。鑒于它們是靜態大小的,我會投入一個static_assert(test.size() <= test2.size());很好的措施。
uj5u.com熱心網友回復:
這是對您要執行的操作的更詳細的答案。不過,我真的不建議使用陣列來保存字串。
#include <array>
#include <iostream>
// copy solution without loops, though probably it would have been more readable with them :)
template<typename type_t, std::size_t N1, std::size_t N2>
void copy_array(const std::array<type_t, N1>& source, std::array<type_t, N2>& destination)
{
// copy to a larger destination
if constexpr (N1 <= N2)
{
// this will copy the whole array! not just the characters from the string literal!
std::copy(source.begin(), source.end(), destination.begin());
// fill remainder of destination with 0's
auto it = destination.begin();
std::advance(it, N1);
std::fill(it, destination.end(), 0);
}
else
// copy into a smaller array, then copy only the beginning
// note this will also result in an array without trailing 0's
// an array is NOT a string.
{
auto end = source.begin();
std::advance(end, N2);
std::copy(source.begin(), end, destination.begin());
}
}
int main()
{
// Note you're probably better of just using const std::strings instead of std::arrays
// this also avoids the pain involved in copying rules for mismatching array sizes.
// The arrays initialized with string literals smaller then their size initialize the
// rest of the array to 0's
std::array<char, 20> test{ "asdasd" };
std::array<char, 19> test2{ "asdassdsdfd" };
copy_array(test2, test);
for (const auto c : test)
{
std::cout << c;
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/354256.html
上一篇:如何將角色轉移到其他部門
下一篇:合并具有相同日期的物件資料
