Dorden
Dorden

Reputation: 45

How can I add something to the middle of a vector without losing data?

I'm trying to add a string to the middle of a vector, but I don't want to lose the data that is being replaced. I want everything below that element to shift down one. Is that possible? Here is what I have so far

#include <iostream>
#include <string>
#include <vector>
using namespace std;

int main()
{
 vector<string> v;

 v.push_back("Rich");
 cout << v.back() << endl;
 v.push_back("Debbie");
 cout << v.back() << endl;
 v.push_back("Robin");
 cout << v.back() << endl;
 v.push_back("Dustin");
 cout << v.back() << endl;
 v.push_back("Philip");
 cout << v.back() << endl;
 v.push_back("Jane");
 cout << v.back() << endl;
 v.push_back("Joseph");
 cout << v.back() << endl;
 cout << "Removing Joseph from the vector"<<endl;
 v.pop_back();

 cout << "Adding my name to the vector" << endl;

 vector<string>::iterator pos = v.find(v.begin(),v.end(), "Robin");
 if (pos != v.end()) 
 {
    ++pos;
 }

 v.insert(pos, "Jimmy");


 cout << "The vector now contains the names:";
 for (unsigned i=0; i<v.size(); i++)
 cout << " " << "\n" << v.at(i);
 cout << "\n";


 return 0;
}

I'm also getting an error on this find function. Any help would be appreciated.

Error   1   error C2039: 'find' : is not a member of 'std::vector<_Ty>' d:\pf3\lab3b\lab3b\3b.cpp   28


    2   IntelliSense: class "std::vector<std::string, std::allocator<std::string>>" has no member "find"    d:\pf3\lab3b\lab3b\3b.cpp   28

Upvotes: 0

Views: 1320

Answers (3)

blackmath
blackmath

Reputation: 252

this operation is O(N) in vector. if you will use it frequently please use linked list.

Upvotes: 0

billz
billz

Reputation: 45410

std::vector has no find function, use std::find instead:

vector<string>::iterator pos = std::find(v.begin(),v.end(), "Robin");

Upvotes: 1

Kerrek SB
Kerrek SB

Reputation: 476990

Like this:

#include <vector>     // for std::vector
#include <algorithm>  // for std::find

v.insert(std::find(v.begin(), v.end(), "Robin"), "Jimmy");

Upvotes: 4

Related Questions