简体   繁体   English

按特定顺序将 2 个数组添加到向量中 c++

[英]Add 2 Arrays into Vector in specific order c++

Suppose I have 2 string arrays,假设我有 2 个字符串数组,

string firstName[John, Jane, Jason];
string middleName[L, M, N];

And a vector of strings,还有一个字符串向量,

vector<string> vec;

Is there a way to add these to the vector in a specific order so that each middle name is with each first name?有没有办法以特定顺序将这些添加到向量中,以便每个中间名与每个名字一起使用? So that when I print out the vector, it would print as:这样当我打印出向量时,它将打印为:

John L约翰·L

Jane M简米

Jason N杰森 N

To add them to the vector I have:要将它们添加到我拥有的向量中:

    vector<string> vec;

    string firstName[] ={"John","Jane","Jason"};
    int N = sizeof(firstName)/ sizeof(firstName[0]);

    for(int i=0; i<N;i++)
        p.push_back(firstName[i]);

    string middleName[]={"L","M","N"};
    N = sizeof(middleName)/ sizeof(middleName[0]);

    for(int i=0; i<N;i++)
        p.push_back(middleName[i]);

But obviously that just prints in a single line "John Jane Jason LMN"但显然这只是打印在一行中“John Jane Jason LMN”

Couldn't add a comment due to reputation.由于声誉问题,无法添加评论。
As Johnny Mopp's comment says, the answer is正如约翰尼莫普的评论所说,答案是

After ensuring they are the same size: for (int i=0; i < N; i++) p.push_back(firstName[i] + " " + middleName[i]);确保它们大小相同后: for (int i=0; i < N; i++) p.push_back(firstName[i] + " " + middleName[i]);

To answer the last comment by OP:要回答 OP 的最后一条评论:
You would of course need to know which person's surname it is.您当然需要知道它是哪个人的姓氏。 If there are n people and m(≤n) surnames, and you have the indices of those people who have surnames, then you just need to modify strings in the vector.如果有 n 个人和 m(≤n) 个姓氏,并且你有那些有姓氏的人的索引,那么你只需要修改向量中的字符串。
For example, if vector p (as above) has a size n, and you have an array LastNamePositions giving the positions of people with surnames, and LastNames stores the last names, then:例如,如果向量p (如上)的大小为 n,并且您有一个数组LastNamePositions给出了姓氏的人的位置,并且LastNames存储了姓氏,那么:

for (int i=0; i<LastNamePositions.size(); i++) {
    p[LastNamePositions[i]] = p[LastNamePositions[i]]+" "+LastNames[i];
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM