RECAP just bc i think we are going to different tangents
I get that I can append an element to an empty vector and immediately print the recently added vector.
the issue was i thought it's possible to add new elements to an existing vector that is NOT empty and print all elements (new and original) concurrently.
as you see in the code i provided, i std::push_back() Pikachu, Charmander, and Squirtle to an empty std::vector called pokemon.
i then attempted to std::insert() an array of strings into pokemon
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
std::vector<std::string> pokemon;
pokemon.push_back("Pikachu"); //adds "Pikachu" to the vector
pokemon.push_back("Charmander"); //adds "Charmander" to the vector
pokemon.push_back("Squirtle"); //adds "Squirtle" to the vector
std::cout << "Traditional std::vector() printing:" << std::endl;
std::cout << pokemon[0] << std::endl; //prints "Pikachu"
std::cout << pokemon[1] << std::endl; //prints "Charmander"
std::cout << pokemon[2] << std::endl; //prints "Squirtle"
std::cout << std::endl;
//HERE IS WHERE I NEED HELP
std::string pokemon_to_add[3] = {"Butterfree", "Onyx", "Arbok"};
pokemon.insert(pokemon.end(), pokemon_to_add, pokemon_to_add + 3);
//I reckon it would be something like:
//for_each(pokemon.begin(), pokemon.end(), [](const auto &i){push_back(i);});
|
markyrocks then suggested that it will be much more legible if i were to append a vector to another opposed to an array of strings to a vector and also so that i won't have to deal with sizes. this is their example:
1 2 3 4
|
vector<string> st{};
vector<string> a{ "abc" , "123", "easy" };
for_each(a.begin(), a.end(), [&st](const auto &i) {st.push_back(i); cout << i; });
|
and so i modeled my code after theirs:
1 2 3 4 5 6 7 8
|
std::vector<std::string> pokemon{};
std::vector<std::string> pokemon_to_add {"Butterfree", "Onyx", "Arbok"};
for_each(pokemon_to_add.begin(), pokemon_to_add.end(), [&](const auto &i) {
pokemon.push_back(i);
std::cout << i << std::endl;
});
|
but the above code only prints the newly added element to an EMPTY vector, which is also mentioned by TheToaster later on.
and then others came with auto range-based and while loop samples along with samples that include pointers. i really appreciated those.
and then mbozzi established that i cannot append new elements to a filled vector and then concurrently print the original + appended vector elements