如何在不丢失数据的情况下向矢量中间添加一些内容
How can I add something to the middle of a vector without losing data?
>我正在尝试在向量的中间添加一个字符串,但我不想丢失正在替换的数据。我希望该元素下面的所有内容都向下移动一个。这可能吗?这是我到目前为止所拥有的
#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:pf3lab3blab3b3b.cpp 28
2 IntelliSense: class "std::vector<std::string, std::allocator<std::string>>" has no member "find" d:pf3lab3blab3b3b.cpp 28
像这样:
#include <vector> // for std::vector
#include <algorithm> // for std::find
v.insert(std::find(v.begin(), v.end(), "Robin"), "Jimmy");
std::vector 没有 find 函数,改用 std::find:
vector<string>::iterator pos = std::find(v.begin(),v.end(), "Robin");
此操作
在向量中为 O(N)。 如果您经常使用它,请使用链表。
相关文章:
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 如何在C++中从两个单独的for循环中添加两个数组
- 2D数组来自文本输入,中间有空格
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- 如何仅为一个函数添加延迟
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将更多文件夹添加到c++include路径
- 如何将元素添加到数组的线程安全函数?
- QT通过C++添加映射QML项目
- 如何将点击的信号和插槽添加到qt中的自定义按钮中
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 如何防止clang格式在流运算符调用之间添加换行符<<
- 我正在尝试在字符数组的中间添加一个空格.不确定如何正确移动它
- 在数组的中间添加新索引
- 为什么要在hash<int>()(foo)的中间添加额外的括号
- 单链表在中间添加节点
- 如何在不丢失数据的情况下向矢量中间添加一些内容
- 添加带有链表的中间节点