Reputation: 710
I have two vectors
typedef std::vector<std::string> messages;
typedef std::vector<std::string> addMessage;
messages st;
addMessage additionlMsgs;
when the user inputs a string i then split that string by a certain character which is then splitted into st
i want to copy that vector over to additionalMsgs at some point but i get a run time error i cannot see why.
i try to copy it over as follows
copy(st.begin(), st.end(), additionlMsgs.begin());
can you see anything that is incorrect?
Thanks Shamari
Upvotes: 0
Views: 132
Reputation: 3354
Using resize is probably a better option in this case.
additionlMsgs.resize(messages.size());
copy(st.begin(), st.end(), additionlMsgs.begin());
This is because additionalMsgs only gets reallocated once, as opposed to multiple times when back_inserter is used.
Upvotes: 0
Reputation: 51283
If you want to append:
additionlMsgs.insert(additionlMsgs.end(), st.begin(), st.end());
If you want to overwrite:
additionlMsgs = st;
Upvotes: 3
Reputation: 500883
It sounds like you're looking for std::back_inserter
:
std::copy(st.begin(), st.end(), std::back_inserter(additionlMsgs));
That'll append to additionlMsgs
. If you wish to overwrite its contents, you might want to use:
additionlMsgs = st;
The code you have right now never adds new elements to additionlMsgs
; it simply overwrites existing ones without performing any bounds checking. If additionlMsgs
is too short, you get undefined behaviour.
Upvotes: 4