将字符串字符映射到矢量
Mapping string characters to vector
请告诉我这种将字符串字符映射到向量的方法有什么问题。
#include <iostream>
#include <string>
#include <vector>
using namespace std;
void strTOvec(string x, vector<string> y) {
for (int i = 0; i < strlen(x.c_str()); i++) {
y.push_back(x[i]);
}
}
void main() {}
收到的错误: E0304、C2664、C4018
std::vector<std::string>
不包含单个字符作为元素,而是包含std::string
对象。std::string
对象始终是字符序列,不能使用直接初始化从单个字符构造std::string
。但这就是您要做的:
y.push_back(x[i]);
// ^^^^ returns a reference to the i-th character in the string
你要么想把向量实例化更改为std::vector<char>
,因此函数签名将是
void strTOvec(string x, vector<char> y)
或者,您可以保留向量类型并使用列表初始化:
y.push_back({x[i]});
// ^ ^ Note the additional braces
但是,这两个选项反映了完全不同的行为。第一个将x
中的每个字符添加到向量或单个字符,第二个将x
中的每个字符转换为长度为 1 的新string
对象,并将此对象添加到向量中。
另请注意,main
必须返回int
。这里的特殊规则:您不必显式返回它。因此,将main
函数更改为
int main() {}
就足够了,而额外的return 0;
也无妨。
有很多错误。
-
main
必须返回一个int
:https://en.cppreference.com/w/cpp/language/main_function -
参数
string x
将不必要地复制您的string
(如果您在调用函数时不移动参数) -
当您尝试将
std::string
的每个char
复制到std::vector
中时,您的std::vector
应该是std::vector<char>
而不是std::vector<std::string>
(https://en.cppreference.com/w/cpp/string/basic_string) -
如果你真的需要使用
std::vector<std::string>
,你需要将你的char
转换为std::string
。有很多方法可以做到这一点。以这种方式修改循环将允许这样做:for (int i = 0; i < strlen(x.c_str()); i++) y.push_back({x[i]});
-
vector<string> y
还将创建一个副本。我猜你正在寻找类似std::vector<char>&
的东西(注意&
,如果你不知道它是什么意思:https://en.cppreference.com/book/intro/reference) -
您的
for
循环有效(如果您的向量y
类型为std::vector<char>
) -
使用返回类型为
void
的函数来修改通过引用传递的参数不是现代C++。也许您更愿意退回std::vector<char>
? -
检查将字符串的字符复制到字符向量中的方式:
std::vector<char> y(x.begin(),x.end());
-
做你的研究,使用CPP首选项,...
- 我如何获取从 C++ 到 C 的映射<字符串、int>#
- 迭代和比较映射<字符串、矢量<string>> c++ 中的值
- 从映射<字符串、矢量中对唯一值进行排序<string>>
- CPP中的映射字符串
- 通过读取文件创建映射<字符串,矢量>时如何管理内存<string>
- Swig:如何类型映射c ++字符串常量和python字符串?
- 如何使用 2 个迭代器进行求和函数计算映射<字符串、双精度>
- 在无序映射<字符串上使用 find(),向量<string>>与 C++ 中的有序映射花费相同的时间
- 使用映射<字符串,结构>类型的映射编译头文件时出错
- 排序标准::映射<字符串,双精度>
- 调用 size() 的常量映射<字符串,矢量<int>>导致错误
- STL 映射<字符串,>与 LLVM 库冲突
- 如何为映射<字符串,映射<字符串,类> >创建迭代器?
- 插入映射<字符串,结构>错误
- 创建多映射<字符串、矢量<string>>
- 动态C++映射<字符串、基元(整数、双精度、字符串或数组)>
- 打印多映射<字符串,矢量<string>>?
- 合并两个映射<字符串,整数>
- 使用 std::transform 打印映射<字符串、矢量<字符串*时出错> >
- 映射<字符串,对象>根据对象成员函数值排序