Date: 2017aug24
Update: 2026sep19
Language: C++
Keywords: push_back, push_front, append
Q. C/C++: How to prepend to a std::vector<>
A. Its slow but this is how you do it:
std::vector<int> a;
a.push_back(200); // Append at the end
a.insert(a.begin(), 100); // Insert at the beginning (prepend)
If you need to do this a lot use a different container like std::list or std::deque. They have push_front();
Example Use:
#include <vector>
#include <string>
std::vector<std::string> a;
int main() {
a.push_back("one");
a.push_back("two");
a.push_back("three");
a.insert(a.begin(), "zero"); // *prepend*
for (auto &s: a) {
printf("element=%s\n", s.c_str());
}
}
Output:
element=zero
element=one
element=two
element=three