简体   繁体   中英

Not declared in scope C++ [Arrays]

I have a quick question. Trying to create a method to print out an array, however, the compiler is telling me that it isn't declared in the scope.

Here's my code:

int main() {
    int theArray[10] = {41, 23, 43, 12, 43, 23, 12, 41, 29, 102};
    printArray(theArray, 10);
}

Here's my printArray method:

void printArray(int arr[], int size) {
    int i;

   for (i = 0; i < size; i ++) {
       std::cout <<" "<< arr[i];
       std::cout << std::endl;
   }
}

Any clue what I'm doing wrong?

Your code is perfectly fine. Just make sure that necessary includes are exist. And the order of the methods:

#include <iostream>
#include <string>

void printArray(int arr[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        std::cout << " " << arr[i];
        std::cout << std::endl;
    }
}

int main() {
    int theArray[10] = { 41, 23, 43, 12, 43, 23, 12, 41, 29, 102 };
    printArray(theArray, 10);
    return 0;
}

Or use forward declaration :

#include <iostream>
#include <string>

void printArray(int arr[], int size);

int main() {
    int theArray[10] = { 41, 23, 43, 12, 43, 23, 12, 41, 29, 102 };
    printArray(theArray, 10);
    return 0;
}

void printArray(int arr[], int size) {
    int i;
    for (i = 0; i < size; i++) {
        std::cout << " " << arr[i];
        std::cout << std::endl;
    }
}

However, you may write it in more C++ modern Style:

1) Using templated function :

#include <iostream>
#include <string>
#include <array>
template<std::size_t N> void printArray(std::array<int, N> x) {
    for (auto const& item:x){
        std::cout << " " << item << std::endl;
    }
}

int main() {
    std::array <int, 10> theArray{ { 41, 23, 43, 12, 43, 23, 12, 41, 29, 102 } };
    printArray<10>(theArray);
    return 0;
}

2)The better by using iterators:

#include <iostream>
#include <string>
#include <array>
template<typename Iterator> void printArray(Iterator beg, Iterator end) {
    for (auto it = beg; it != end; it = std::next(it)){
        std::cout << " " << *it << std::endl;
    }
}

int main() {
    std::array <int, 10> theArray{ { 41, 23, 43, 12, 43, 23, 12, 41, 29, 102 } };
    printArray(std::begin(theArray), std::end(theArray));
    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM