[英]Printing an array in C++?
有沒有辦法在C++中打印arrays?
我正在嘗試制作一個 function 來反轉用戶輸入數組,然后將其打印出來。 我嘗試用谷歌搜索這個問題,似乎 C++ 無法打印 arrays。這不可能是真的吧?
只需迭代元素。 像這樣:
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<> 。 這是一個利用(現已停用)SGI STL 參考中的示例代碼的示例:
#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
但是,這對於您的需求來說可能有點過頭了。 一個直接的 for 循環可能就是你所需要的,盡管litb 的模板糖也很不錯。
編輯:忘記了“反向打印”要求。 這是一種方法:
#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
編輯:C++14 更新使用像std::begin()和std::rbegin()這樣的數組迭代器函數來簡化上面的代碼片段:
#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++ 中常用的大多數庫本身都不能打印數組。 您必須手動遍歷它並打印出每個值。
打印數組和轉儲許多不同類型的對象是高級語言的一個特性。
那當然是! 您必須遍歷數組並單獨打印出每個項目。
有沒有一種方法可以在C ++中打印數組?
我正在嘗試制作一個功能,該功能可以反轉用戶輸入數組,然后將其打印出來。 我嘗試了Google搜索這個問題,似乎C ++無法打印數組。 那不是真的嗎?
這可能有助於//打印數組
for (int i = 0; i < n; i++)
{cout << numbers[i];}
n 是數組的大小
我的簡單回答是:
#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;
}
std::string ss[] = { "qwerty", "asdfg", "zxcvb" };
for ( auto el : ss ) std::cout << el << '\n';
工作原理與 foreach 類似。
在 C++ 中,您可以通過以下方式簡單地打印數組:
for (int i = 0; i < numberOfElements; i++) {
cout << arr[i] << " ";
}
// 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;
}
}
不能僅通過將數組傳遞給函數來打印數組。 因為c++中沒有這樣的函數。 像這樣做:
for (auto x = std::end(a); x != std::begin(a); ) { std::cout <<*--x<< ' '; }
或者你可以使用這個: https : //github.com/gileli121/VectorEx
您可以使用DisplayVector_1d()輕松顯示數組。 它是在visual studio 2015下開發的。只能在windows下運行(在Windows 7 64位上測試)。
你在這個庫中看到的是DisplayVector_1d。 一世
它將在listview GUI中顯示該數組。 它就像Autoit中的_ArrayDisplay函數。
這是一個如何使用它的示例:
// includes.functions
#include <windows.h>
#include "VectorEx\VectorEx.h"
#include "VectorEx\VectorDisplay.h"
using namespace vectorex;
using namespace vectordisplay;
/*
This example shows how to use display std::vector array datatype
with vectordisplay::DisplayVector_1d
*/
int main()
{
std::vector<std::string> stringVector;
stringVector.push_back("Bob");
stringVector.push_back("Fob");
stringVector.push_back("Rob");
stringVector.push_back("Nob");
DisplayVector_1d(&stringVector);
return 0;
}
請注意,我剛剛開始研究這個項目。 歡迎您改進代碼並修復錯誤
如果你想制作一個 function 來打印數組中的每個元素;
#include <iostream>
using namespace std;
int myArray[] = {1,2,3,4, 77, 88};
void coutArr(int *arr, int size){
for(int i=0; i<size/4; i++){
cout << arr[i] << endl;
}
}
int main(){
coutArr(myArray, sizeof(myArray));
}
上面的 function 僅打印數組中的每個元素,而不是逗號等。
您可能想知道“為什么 sizeoff(arr) 除以 4?”。 這是因為如果數組中只有一個元素,cpp 會打印 4。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.