How can I join two std::vectors?

Started by
4 comments, last by swiftcoder 14 years, 7 months ago
Hi dudes! Let's say I have std::vector<CWhatever*> v1; and std::vector<CWhatever*> v2; How can I join them? I mean, is there any easy way or a method that do that? (I already can do that using 2 fors) Thanks for replies.
I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the dark near the Tannhauser gate. All those moments will be lost in time, like tears in rain. Time to die.
Advertisement
If by join, you mean insert the contents of one to the end of the other you can use: v1.insert(v1.end(), v2.begin(), v2.end()).
Notice that won't remove doubles if both list contains the same item. If it were a list, you could use list::sort(); list::erase(list::unique()) for that.
Using a container of raw pointers suggests a design problem. Consider using one of the boost ptr_containers (boost::ptr_vector in this case), or a container of smart pointers (e.g. std::vector<boost::shared_ptr> - note that std::auto_ptr is *not* suitable for storing in a standard library container; if you have a good implementation, it should produce a compiler error instead of undefined behaviour). The exact choice depends on why you are using pointers currently. (It may even be the case that an ordinary vector of instances is the correct solution.)
Quote:Original post by SiCrane
If by join, you mean insert the contents of one to the end of the other you can use: v1.insert(v1.end(), v2.begin(), v2.end()).


OK, I'll use that. I guess I can use something like that using a third vector.

Thanks.
I've seen things you people wouldn't believe. Attack ships on fire off the shoulder of Orion. I watched C-beams glitter in the dark near the Tannhauser gate. All those moments will be lost in time, like tears in rain. Time to die.
Also worth considering whether std::vector is the right tool for the job - std::list has splice functionality which is typically O(1), as opposed to O(n) for the vector equivalent.

Tristam MacDonald. Ex-BigTech Software Engineer. Future farmer. [https://trist.am]

This topic is closed to new replies.

Advertisement