这是我在C ++中学习的数组。有什么方法可以进一步简化这个吗?
cout<< "整数值数组" << ENDL; cout<< " =======================" << ENDL;
int value[5] = { 17, 34, 51, 68, 85 }; // Creates an integer array list that contain a series of 5 values
for (int loop = 0; loop < 5; loop++) {
cout << "Integer value " << loop << ": " << value[loop] << endl;
}
cout << endl << "Array of double values" << endl; // First endl creates a blank line
cout << "=======================" << endl;
double numbers[10] = { 12.1, 24.2, 36.3, 48.4, 60.5, 72.6, 84.7, 96.8, 212.9, 3.0 }; // Creates an double integer array list that contains a series of 10 values
for (int loop = 0; loop < 10; loop++) { // Loops array
// Adding example " numbers[loop] = 77; " would set every number to 77
cout << "Element at index " << loop << ": " << numbers[loop] << endl;
}
cout << endl << "Initializing with zero values" << endl; // First endl creates a blank line
cout << "=======================" << endl;
for (int loop = 0; loop < 1; loop++) { // Loops array
// Adding " numbers[loop] = 77; " would set every number to 77
cout << "Element at index " << loop << ": " << numbers[loop] << endl;
}
cout << endl << "Initializing with strings" << endl; // First endl creates a blank line
cout << "=======================" << endl;
// Array of strings
string text = ( "Chair", "Table", "Plate" ) ;
; for (int loop = 0; loop < 3; loop++) { // Loops array
cout << "Element at index " << loop << ": " << text[loop] << endl;
return 0;
答案 0 :(得分:1)
你永远不会使用你在这里声明的数组:
int numberArray[8] = {};
这整个部分看起来像是从上面重复:
for (int loop = 0; loop < 10; loop++) { // Loops array // Adding " numbers[loop] = 77; " would set every number to 77 cout << "Element at index " << loop << ": " << numbers[loop] << endl;
就“简化”这个问题而言,如果你使用相同数据类型的数组,你可以编写一个接受数组的函数,元素的数量,以及通过数组输出的任何你想要的循环。然后,您可以每次从main
函数调用此函数,而不是重复for
循环
答案 1 :(得分:0)
也许你可以尝试这样的事情:
template <typename T>
void Printer (const vector<T> &t_elementsToPrint)
{
// For simple value printing
for (auto value : t_elementsToPrint)
cout << value << "\n";
// If you want to know the index number
for (auto it = begin(t_elementsToPrint); it != end(t_elementsToPrint); ++it)
{
cout << "Element at index " << distance(begin(t_elementsToPrint), it) << " : " << *it << "\n";
}
}
int main (int argc, char* argv[])
{
vector<double> numbers = { 12.1, 24.2, 36.3, 48.4, 60.5, 72.6, 84.7, 96.8, 212.9, 3.0 }; // Creates an double integer array list that contains a series of 10 values
Printer<double>(numbers);
vector<int> numbers2 = { 17, 34, 51, 68, 85 };
Printer<int>(numbers2);
return 0;
}
您可以将容器从矢量更改为数组或其他可能适合您的容器,除非您确实需要原始访问权限,如果您要查找的是简单性,我建议您坚持使用STL容器。