c++ - 我的 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++ 相当陌生。
解决方案
首先,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;
}
推荐阅读
- dart - 使用 @Relate 和唯一
- graph - 网格上下文变量未传递给页面查询
- java - 如何以编程方式禁用 S3 公共访问
- xcode10.2 - 如何加载和应用到我的设备上进行测试
- node.js - 为什么 typescript-eslint 没有在 TypeScript 上指定 peerDependency?
- javascript - 重新挂载组件并更改其状态
- python - 为什么我的 if 语句不能正常工作?
- javascript - 单击箭头按钮时如何更快地移动矩形?
- algorithm - 可以在 O(n) 或 O(1) 时间内计算出第 n 个斐波那契数吗?为什么?
- java - 如何将java堆转储分解成更小的部分?