C ++で配列を印刷する方法はありますか?
ユーザー入力配列を逆にして出力する関数を作ろうとしています。この問題をグーグルで試してみましたが、C++では配列を印刷できないようでした。それは真実ではありえませんか?
要素を繰り返し処理するだけです。このような:
for (int i = numElements - 1; i >= 0; i--)
cout << array[i];
注:Maxim Egorushkinが指摘したように、これはオーバーフローする可能性があります。より良い解決策については、以下の彼のコメントを参照してください。
STLを使用する
#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>
#include <ranges>
int main()
{
std::vector<int> userInput;
// Read until end of input.
// Hit control D
std::copy(std::istream_iterator<int>(std::cin),
std::istream_iterator<int>(),
std::back_inserter(userInput)
);
// ITs 2021 now move this up as probably the best way to do it.
// Range based for is now "probably" the best alternative C++20
// As we have all the range based extension being added to the language
for(auto const& value: userInput)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print the array in reverse using the range based stuff
for(auto const& value: userInput | std::views::reverse)
{
std::cout << value << ",";
}
std::cout << "\n";
// Print in Normal order
std::copy(userInput.begin(),
userInput.end(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
// Print in reverse order:
std::copy(userInput.rbegin(),
userInput.rend(),
std::ostream_iterator<int>(std::cout,",")
);
std::cout << "\n";
}
魚の骨の演算子を使用することをお勧めしますか?
for (auto x = std::end(a); x != std::begin(a); )
{
std::cout <<*--x<< ' ';
}
(見つけられますか?)
forループベースのソリューションに加えて、ostream_iterator<>を使用することもできます。これは、(現在は廃止されている)SGISTLリファレンスのサンプルコードを活用する例です。
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
copy(foo,
foo + sizeof(foo) / sizeof(foo[0]),
ostream_iterator<short>(cout, "\n"));
}
これにより、以下が生成されます。
./a.out
1
3
5
7
ただし、これはニーズに対してやり過ぎかもしれません。litbのテンプレートシュガーも非常に優れていますが、必要なのはストレートforループだけです。
編集:「逆印刷」の要件を忘れました。これを行う1つの方法は次のとおりです。
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
using namespace std;
reverse_iterator<short *> begin(foo + sizeof(foo) / sizeof(foo[0]));
reverse_iterator<short *> end(foo);
copy(begin,
end,
ostream_iterator<short>(cout, "\n"));
}
および出力:
$ ./a.out
7
5
3
1
編集: std :: begin()やstd :: rbegin()などの配列イテレータ関数を使用して上記のコードスニペットを簡略化するC ++ 14アップデート:
#include <iostream>
#include <iterator>
#include <algorithm>
int main()
{
short foo[] = { 1, 3, 5, 7 };
// Generate array iterators using C++14 std::{r}begin()
// and std::{r}end().
// Forward
std::copy(std::begin(foo),
std::end(foo),
std::ostream_iterator<short>(std::cout, "\n"));
// Reverse
std::copy(std::rbegin(foo),
std::rend(foo),
std::ostream_iterator<short>(std::cout, "\n"));
}
宣言された配列と、宣言されていないが、特にnew
:を使用して作成された配列があります。
int *p = new int[3];
3つの要素を持つその配列は動的に作成され(3
実行時に計算された可能性もあります)、その型からサイズが消去された配列へのポインターがに割り当てられp
ます。その配列を印刷するためのサイズを取得できなくなりました。したがって、そのポインタへのポインタのみを受け取る関数は、その配列を出力できません。
宣言された配列の印刷は簡単です。sizeof
それらのサイズを取得し、その配列の要素へのポインターを含む関数にそのサイズを渡すために使用できます。ただし、配列を受け入れ、宣言された型からそのサイズを推測するテンプレートを作成することもできます。
template<typename Type, int Size>
void print(Type const(& array)[Size]) {
for(int i=0; i<Size; i++)
std::cout << array[i] << std::endl;
}
これに伴う問題は、(明らかに)ポインタを受け入れないことです。最も簡単な解決策は、を使用することだと思いますstd::vector
。これは動的でサイズ変更可能な「配列」(実際の配列に期待されるセマンティクスを備えたもの)であり、size
メンバー関数があります。
void print(std::vector<int> const &v) {
std::vector<int>::size_type i;
for(i = 0; i<v.size(); i++)
std::cout << v[i] << std::endl;
}
もちろん、これをテンプレートにして、他のタイプのベクトルを受け入れることもできます。
C ++で一般的に使用されるライブラリのほとんどは、配列自体を出力できません。手動でループして、各値を出力する必要があります。
配列の印刷とさまざまな種類のオブジェクトのダンプは、高級言語の機能です。
確かにそうです!配列をループして、各アイテムを個別に印刷する必要があります。
私の簡単な答えは:
#include <iostream>
using namespace std;
int main()
{
int data[]{ 1, 2, 7 };
for (int i = sizeof(data) / sizeof(data[0])-1; i >= 0; i--) {
cout << data[i];
}
return 0;
}
これは//配列の印刷に役立つ可能性があります
for (int i = 0; i < n; i++)
{cout << numbers[i];}
nは配列のサイズです
std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';
基本的にforeachのように機能します。
// Just do this, use a vector with this code and you're good lol -Daniel
#include <Windows.h>
#include <iostream>
#include <vector>
using namespace std;
int main()
{
std::vector<const char*> arry = { "Item 0","Item 1","Item 2","Item 3" ,"Item 4","Yay we at the end of the array"};
if (arry.size() != arry.size() || arry.empty()) {
printf("what happened to the array lol\n ");
system("PAUSE");
}
for (int i = 0; i < arry.size(); i++)
{
if (arry.max_size() == true) {
cout << "Max size of array reached!";
}
cout << "Array Value " << i << " = " << arry.at(i) << endl;
}
}