while(数组结束) - 如何识别

Lil*_*ila 4 c++ arrays templates while-loop

我有一组数字{1,2,3,4,5}或一组字符或其他什么.我想写一个模板方法来打印出完整的数组.它有效,只有一些问题.也许我先发布代码:

template <typename A>
void printArray(A start) {
    int i = 0;
    while (start[i] != 0) {
        std::cout << start[i] << std::endl;
        i++;
    }
}

int main(int argc, char **argv) {

    using namespace std;
    int xs[] = {1,2,3,4,5,6,7}; //works
    //int xs[] = {1,0,3,6,7}; of course its not working (because of the 0)
    int *start = xs;

    printArray(start);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

你能看到问题吗?while(start[i] != 0)不是读取数组结束的最佳方式;)我有什么其他选项?

谢谢!

Arm*_*yan 12

选项1:传递指针和元素数量

 template<class T>
 void doSth(T* arr, int size)
Run Code Online (Sandbox Code Playgroud)

上行 - 将适用于动态和自动阵列.
缺点 - 您必须知道尺寸.你必须通过它.

选项2:使用将自动推导的大小参数化模板

template <class T, int N>
void doSth(T(&arr)[N])
Run Code Online (Sandbox Code Playgroud)

缺点 - 无法传递动态数组

选择3:做一个优秀的程序员和使用std::vector


Dan*_*ite 11

由于使用的是C++中,vector<int>并且iterators会做得更好,你从长远来看.


Naw*_*waz 6

如果要使用数组而不是指针,则可以将函数模板编写为:

template <typename T, size_t N>
void printArray(T (&start)[N]) 
{
    int i = 0;
    while ( i < N) {
        std::cout << start[i] << std::endl;
        i++;
    }
}

int xs1[] = {1,2,3,4,5,6,7}; 
int xs2[] = {1,0,3,6,7}; 
printArray(xs1); //okay
printArray(xs2); //okay

int *start = xs1;
printArray(start); //error - cannot pass pointer anymore!
Run Code Online (Sandbox Code Playgroud)

所以更好的解决方案是:std::vector<T>.

或者甚至更好地使用非常惯用的范围(迭代器对),如:

template <typename FwdIterator>
void printArray(FwdIterator begin, FwdIterator end) 
{
    while (begin != end) {
        std::cout << *begin << std::endl;
        begin++;
    }
}

int xs1[] = {1,2,3,4,5,6,7}; 
int xs2[] = {1,0,3,6,7}; 
printArray(xs1, xs1 + sizeof(xs1)/sizeof(xs1[0])); //okay
printArray(xs2, xs2 + sizeof(xs2)/sizeof(xs2[0])); //okay

int *start = xs1;
printArray(start, start + sizeof(xs1)/sizeof(xs1[0])); //okay!
Run Code Online (Sandbox Code Playgroud)

printArray现在也可以用std::vector<T>:

std::vector<int> vec; //you can use std::list as well!
//populate vec

printArray(vec.begin(), vec.end());
Run Code Online (Sandbox Code Playgroud)