0

我正在尝试将字符串添加到向量的中间,但我不想丢失正在被替换的数据。我希望该元素下方的所有内容都向下移动一个。那可能吗?这是我到目前为止所拥有的

#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;
}

我在这个查找功能上也遇到了错误。任何帮助,将不胜感激。

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
4

3 回答 3

4

像这样:

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

v.insert(std::find(v.begin(), v.end(), "Robin"), "Jimmy");
于 2013-02-01T00:13:41.437 回答
1

std::vector没有查找功能,请改用std::find

vector<string>::iterator pos = std::find(v.begin(),v.end(), "Robin");
于 2013-02-01T00:15:29.130 回答
0

这个操作在向量中是 O(N)。如果你会经常使用它,请使用链表。

于 2013-02-01T22:09:11.040 回答