71

C ++で配列を印刷する方法はありますか?

ユーザー入力配列を逆にして出力する関数を作ろうとしています。この問題をグーグルで試してみましたが、C++では配列を印刷できないようでした。それは真実ではありえませんか?

4

11 に答える 11

69

要素を繰り返し処理するだけです。このような:

for (int i = numElements - 1; i >= 0; i--) 
    cout << array[i];

注:Maxim Egorushkinが指摘したように、これはオーバーフローする可能性があります。より良い解決策については、以下の彼のコメントを参照してください。

于 2009-09-02T21:52:28.573 に答える
51

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

}
于 2009-09-02T22:26:32.437 に答える
37

魚の骨の演算子を使用することをお勧めしますか?

for (auto x = std::end(a); x != std::begin(a); )
{
    std::cout <<*--x<< ' ';
}

(見つけられますか?)

于 2013-03-08T18:10:21.080 に答える
14

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"));
}
于 2009-09-02T22:08:47.353 に答える
7

宣言された配列と、宣言されていないが、特に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;
}

もちろん、これをテンプレートにして、他のタイプのベクトルを受け入れることもできます。

于 2009-09-02T21:55:56.397 に答える
4

C ++で一般的に使用されるライブラリのほとんどは、配列自体を出力できません。手動でループして、各値を出力する必要があります。

配列の印刷とさまざまな種類のオブジェクトのダンプは、高級言語の機能です。

于 2009-09-02T21:51:58.090 に答える
3

確かにそうです!配列をループして、各アイテムを個別に印刷する必要があります。

于 2009-09-02T21:52:05.313 に答える
1

私の簡単な答えは:

#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;
}
于 2018-07-23T22:22:21.400 に答える
1

これは//配列の印刷に役立つ可能性があります

for (int i = 0; i < n; i++)
{cout << numbers[i];}

nは配列のサイズです

于 2018-12-01T15:16:14.893 に答える
1
std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';

基本的にforeachのように機能します。

于 2021-09-06T18:17:42.590 に答える
-1
// 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;
            
    }
}
于 2021-01-04T09:17:53.697 に答える