'Add 2 Arrays into Vector in specific order c++
Suppose I have 2 string arrays,
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
Jane M
Jason 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 L M N"
Solution 1:[1]
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]);
To answer the last comment by 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.
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:
for (int i=0; i<LastNamePositions.size(); i++) {
p[LastNamePositions[i]] = p[LastNamePositions[i]]+" "+LastNames[i];
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | abs |
