Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/125.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++ - Fatal编程技术网

C++ 函数,该函数将一个元素插入到向量中,并置换所有其他元素,截断最后一个元素

C++ 函数,该函数将一个元素插入到向量中,并置换所有其他元素,截断最后一个元素,c++,C++,我试图编写一个函数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);

我试图编写一个函数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;
//插入向量函数:
int-InsertVector(向量V、int-sz、int-pos、int-elem){
int tmp=V.at(sz-1);
V.插入(V.开始()+位置1,要素);

对于(int i(pos);i您不需要将所有值向右移位。
V.insert()
将自行完成此操作。您只需删除最后一个元素即可截断列表。要删除最后一个元素,请使用
V.pop\u back()

如果您知道需要向量中的条目数,则不应引入诸如
sz
之类的无关变量。这样做会增加传递错误值的机会。请改用
vector::size()
方法。此外,如果向量为空,该怎么办?啊,好的,谢谢!我将尝试再次编写它
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);


}
void PrintVector(const vector <int> v1, int sz) {

    for (int i(0);i<sz;i++) {

        cout<<"V["<<i<<"] ="<<v1[i]<<endl;

    }

}