如何将单个矢量转换为多个字符串

How to convert single vector to multiple strings?

本文关键字:字符串 转换 单个矢      更新时间:2023-10-16

我有一个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;

当然,我现在只是打印它们来测试,以确保它正确分配,我现在可以继续实际编码,我希望它如何操作名称。

谢谢你的帮助!