如何将单个矢量转换为多个字符串
How to convert single vector to multiple strings?
我有一个C++代码,它接受多个字符串,将它们全部添加到一个向量中,并按字母顺序对它们进行排序,但我需要它来重新拆分该向量,并将其值分配回各个字符串。我该怎么做?我已经到处搜索了为多个字符串分配向量的方法,但只找到了从字符串到向量的方法。
我有矢量"名称",我想将其分配给多个字符串,这些字符串对应于矢量"名称"中的名称顺序,例如:
输入:
"John Dave Peter Charlie Michael"
代码将它们分解并按字母顺序排列,但现在我想将它们重新分配给向量中每个名称的字符串"str1"、"str2"、"str3"、"tr4"等(向量的名称永远不会超过20个,所以现在我只是单独定义每个字符串)。
最后我希望能够添加
cout << str1 << endl
cout << str2 << endl
等等。并得到输出:
Charlie
Dave
约翰·
Michael
Peter
(在显示名称之前,我将进一步操作这些名称,因此简单地立即显示整个矢量不会有任何好处)。非常感谢!
----编辑----
如果我现在输入,评论不会让我返回
cout << names[0] << endl
我下车:
Charlie
Charlie
Charlie
Charlie
Charlie
----编辑----
当前代码:
vector<string> separate_string(const string& input)
{
istringstream input_stream(input);
string buffer;
vector<string> separated;
while (input_stream >> buffer)
{
separated.push_back(buffer);
}
return separated;
}
int main()
{
string test_string;
getline(cin, test_string);
auto names = separate_string(test_string);
//sort(begin(names), end(names));
//for (const auto& s : names)
//string temp1;
cout << names[0] << endl;
}
您想要的是一个容器来容纳它们:
vector<string> my_strings {"John", "Dave", "Peter", "Charlie", "Michael"};
然后对进行排序:
std::sort(my_strings.begin(), my_strings.end());
然后将打印到stdout:
std::copy(my_strings.begin(), my_strings.end(), std::ostream_iterator<string>(std::cout, "n"));
好的,
我很抱歉,我想我很困惑我到底在寻找什么,我想好了怎么做,我只是不知道索引向量的能力(是的,我是个十足的傻瓜)。
我最终解决了它,但只是用一个索引定义了每个字符串:
string test_string;
getline(cin, test_string);
auto names = separate_string(test_string);
//sort(begin(names), end(names));
//for (const auto& s : names)
string temp1 = names[0];
cout << temp1 << endl;
string temp2 = names[1];
cout << temp2 << endl;
string temp3 = names[2];
cout << temp3 << endl;
string temp4 = names[3];
cout << temp4 << endl;
当然,我现在只是打印它们来测试,以确保它正确分配,我现在可以继续实际编码,我希望它如何操作名称。
谢谢你的帮助!
相关文章:
- 如何将包含epoch时间的十六进制字符串转换为time_t
- 当字符串存储在变量中时,如何将字符串转换为wchar_t
- 如何将这个std::字符串转换为std::基本字符串
- 如何正确将字符串转换为标准::时间::system_clock::time_point?
- 如何在C++中将十六进制字符串转换为文本数据
- 需要帮助在 c++ 中将字符串转换为字符 ----错误 "const char *" 类型的值不能用于初始化 "char" 类型的实体
- 如何从字符串转换为双精度*
- C++:如何将 unix 时间的字符串转换为 *tm?(使用时间错误:"cannot convert 'String' to 'tm*' ")
- 如何在C++中将 Python 字符串转换为其转义版本?
- 如何在 C++11 中将标准::字符串转换为标准::u32字符串?
- 如何将整数字符串转换为整数的二维向量?
- 使用 "stringstream " 将字符串转换为整数
- 将字符串转换为浮点数或整数,而无需使用内置函数(如 atoi 或 atof)
- 将文件复制到自定义位置,存在字符串转换问题
- 将ANSI C字符串转换为UNICODE
- 如何将节点 V8 字符串转换为 C++ 字符串
- 在C++中将字符串转换为双精度,而无需科学记数法
- 使用从文件(stod、strtod、atof)中提取的数据C++从字符串转换为双精度.csv
- 如何在C++中将字符串转换为双精度?
- 将字符串转换为无符号字符数组/字节数组