Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/161.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何在不丢失数据的情况下向向量中间添加内容?_C++_Vector - Fatal编程技术网

C++ 如何在不丢失数据的情况下向向量中间添加内容?

C++ 如何在不丢失数据的情况下向向量中间添加内容?,c++,vector,C++,Vector,我试图在向量的中间添加一个字符串,但我不想丢失被替换的数据。我希望元素下面的所有元素都向下移动一个。可能吗? 这是我到目前为止所拥有的 #include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> v; v.push_back("Rich"); cout << v.back() &

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

#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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
向量v;
v、 推回(“富”);
不能像这样:

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

v.insert(std::find(v.begin(), v.end(), "Robin"), "Jimmy");
#包含//用于std::vector
#include//for std::find
v、 插入(std::find(v.begin(),v.end(),“Robin”),“Jimmy”);
像这样:

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

v.insert(std::find(v.begin(), v.end(), "Robin"), "Jimmy");
#包含//用于std::vector
#include//for std::find
v、 插入(std::find(v.begin(),v.end(),“Robin”),“Jimmy”);
没有查找功能,请改用:

vector::iterator pos=std::find(v.begin(),v.end(),“Robin”);
没有查找功能,请改用:

vector::iterator pos=std::find(v.begin(),v.end(),“Robin”);

此操作是矢量中的O(N)。如果您经常使用它,请使用链表。

此操作是矢量中的O(N)。如果您经常使用它,请使用链表。

此操作插入之前而不是之后。哇,这正是我需要的。谢谢!我正要放弃并删除“Robin”她下面的每个人,在我插入我的名字后重新添加。非常感谢!这是在之前而不是之后插入的。哇,这正是我需要的。谢谢!我正要放弃并删除“罗宾”和她下面的每个人,在我插入我的名字后重新添加他们。非常感谢!
vector<string>::iterator pos = std::find(v.begin(),v.end(), "Robin");