将字符串字符映射到矢量

Mapping string characters to vector

本文关键字:映射 字符串 字符      更新时间:2023-10-16

请告诉我这种将字符串字符映射到向量的方法有什么问题。

#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首选项,...