我正在尝试编写一个函数InsertVector,它将元素( elem )插入位置 pos 的向量中,然后将所有其他值替换为右侧,截断向量的最后一个值并返回其值; sz 是矢量的大小。
以下是代码:
//InsertVector function:
int InsertVector (vector <int> V, int sz, int pos, int elem) {
int tmp=V.at(sz-1);
V.insert(V.begin()+pos-1, elem);
for(int i(pos);i<=sz-2;i=i+1) {
int tmp2(V.at(i));
V.at(i)=V.at(i-1);
V.at(i+1)=tmp2;
}
return tmp;
这是我尝试在main上测试函数:
int main() {
vector<int>V;
V.push_back(2);
V.push_back(3);
V.push_back(4);
int sz(0);
sz=V.size();
int pos(0);
int elem(0);
cout<<"enter the position desired to modify here"<<endl;
cin>>pos;
cout<<"enter value to replace with here"<<endl;
cin>>elem;
InsertVector(V, sz, pos, elem);
PrintVector(V, sz);
}
注意:PrintVector是我创建的另一个函数,用于打印向量的元素,并具有以下格式:
void PrintVector(const vector <int> v1, int sz) {
for (int i(0);i<sz;i++) {
cout<<"V["<<i<<"] ="<<v1[i]<<endl;
}
}
当我编译Xcode时出错(lldb)。
提前谢谢。
答案 0 :(得分:0)
您无需将所有值替换为右侧。 V.insert()
会自己做到这一点。您可以删除最后一个元素以截断列表。要删除最后一个元素,请使用v.pop_back()