首页 > 解决方案 > 我的 C++ 尝试转换 std::vector到 JSON 不编译

问题描述

我正在尝试将我用 JavaScript 编写的程序移植到 C++ 以使其更快。在那个程序中,我处理了一些 JSON。因此,我尝试制作一种将字符串向量转换为 JSON 的方法:

#include <iostream>
#include <vector>
#include <string>

class std::vector<std::string> {
    public: std::string JSON();
};

std::string std::vector<std::string>::JSON() {
    std::string ret="[";
    if (this->size()==0) {
        ret+="]";
        return ret;
    }
    int currentSize=this->size();
    for (int i=0; i<currentSize; i++) {
        if (i!=currentSize-1)
            ret+="\""+this->operator[](i)+"\",";
        else
            ret+="\""+this->operator[](i)+"\"]";
    }
    return ret;
}

int main(int argc, char **argv) {
    std::vector<std::string> fieldOfStrings({"Hello","world","!"});
    std::cout <<fieldOfStrings.JSON() <<std::endl;
    return 0;
}

但是,它不会编译:

/home/teo.samarzija/Documents/AECforWebAssembly/AECforWebAssembly.cpp:5:12: error: too few template-parameter-lists
 class std::vector<std::string> {
            ^
/home/teo.samarzija/Documents/AECforWebAssembly/AECforWebAssembly.cpp:9:13: error: specializing member 'std::vector<std::basic_string<char> >::JSON' requires 'template<>' syntax
 std::string std::vector<std::string>::JSON() {

我究竟做错了什么?我对 C++ 相当陌生。

标签: c++jsonvector

解决方案


首先,class std::vector<std::string>没有意义。其次,不需要类,因为您可以定义一个类似于您的成员函数的函数,该函数接收std::vector<std::string>并返回 json 字符串。

例如:

#include <iostream>
#include <vector>
#include <string>

std::string JSON(std::vector<std::string> str) {
    std::string ret="[";
    if (str.size()==0) {
        ret+="]";
        return ret;
    }
    int currentSize=str.size();
    for (int i=0; i<currentSize; i++) {
        if (i!=currentSize-1)
            ret+="\""+str[i]+"\",";
        else
            ret+="\""+str[i]+"\"]";
    }
    return ret;
}

int main(int argc, char **argv) {
    std::vector<std::string> fieldOfStrings({"Hello","world","!"});
    std::cout <<JSON(fieldOfStrings) <<std::endl;
    return 0;
}

推荐阅读