c++ - vector 的 vector 的 vector 之和......整数

标签 c++ templates vector

我正在尝试对一个 vector 的 vector 的 vector 的所有元素求和...整数:类似于 std::vector<std::vector<std::vector<std::vector<int>>>>不需要每一层都具有相同的大小。

我想用模板来完成,所以我这样做了:

namespace nn
{
    template < class T >
    int sumAllElements(std::vector<T> v)
    {
        int size = v.size();
        int output = 0;

        for ( int i = 0 ; i < size ; i++ )
        {
                                                //should call the function below 
            output += sumAllElements( v[ i ] ); //or this function, depending in 
                                                //which "layer" we are
        }

        return output;
    }

    int sumAllElements(std::vector<int> v)
    {
        int size = v.size();
        int output = 0;

        for ( int i = 0 ; i < size ; i++ )
        {
            output += v[ i ]; //we've reached the bottomest layer,
                              //so just sum everybory
        }

        return output;
    }
}

但是,这正在发生:

CMakeFiles\test.dir/objects.a(main.cpp.obj): In function `main':
D:/test/main.cpp:49: undefined reference to `int nn::sumAllElements<std::vector<int, std::allocator<int> > >(std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >)'
collect2.exe: error: ld returned 1 exit status
mingw32-make.exe[3]: *** [CMakeFiles\test\build.make:141: test.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles\Makefile2:67: CMakeFiles/test.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles\Makefile2:79: CMakeFiles/test.dir/rule] Error 2
mingw32-make.exe: *** [Makefile:117: test] Error 2

我真的不知道为什么...

提前致谢。

最佳答案

正在阅读您的错误消息。看起来您的函数位于与 main.cpp 不同的编译单元中。如果您的函数在 .h 文件中,#include main.cpp 中的头文件。

我建议使用模板特化声明:

template<>
int sumAllElements(std::vector<int> v)
{
 ...   
}

另一个不相关的建议是通过常量引用传递 vector 。目前,您正在按值传递它们,如果 vector 很大,这可能代价高昂。

关于c++ - vector 的 vector 的 vector 之和......整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47165257/

相关文章:

c++ - 插入队列期间内存泄漏

c++ - SFINAE enable_if 显式构造函数

c++ - 从 bool vector 返回索引的 int 函数

javascript - mustache.js 与 jquery-tmpl

python - 过滤循环中的循环变量

c++ - 在 C++ 中输入空白行之前,如何要求用户输入整数?

c++ - 如何在 C++ 中反转字符串 vector ?

c++ - target_link_libraries 调用后链接路径困惑

c++ - 分割故障QPainter

c++ - 在 const 方法中修改指针值