push_back一个向量到另一个向量中

push_back a vector into another vector

本文关键字:向量 一个 另一个 back push      更新时间:2023-10-16

我想push_back()向量M到向量N中。

#include <iostream>
#include <vector>
using namespace std;
int main()
{
    int i = -1;
    vector<vector<int> >N,
    vector<int>M;
    int temp;
    while (i++ != 5)
    {
        cin >> temp;
        N.push_back(temp);
    }
    N.push_back(vector<int>M);
    return 0;
}

编译错误

我收到语法错误。

test.cpp: In function ‘int main()’:
test.cpp:28: error: invalid declarator before ‘M’
test.cpp:34: error: no matching function for call to ‘std::vector<std::vector<int, std::allocator<int> >, std::allocator<std::vector<int, std::allocator<int> > > >::push_back(int&)’
/usr/include/c++/4.4/bits/stl_vector.h:733: note: candidates are: void std::vector<_Tp, _Alloc>::push_back(const _Tp&) [with _Tp = std::vector<int, std::allocator<int> >, _Alloc = std::allocator<std::vector<int, std::allocator<int> > >]
test.cpp:37: error: ‘M’ was not declared in this scope
coat@thlgood:~/Algorithm$ 
N.insert(N.end(),M.begin(),M.end());

此行

N.push_back(vector<int>M);

应该是

N.push_back(M);

vector<vector<int> >N,

应该是

vector<vector<int> >N;

你需要

M.push_back(temp);

在 while 循环中,除了 @StilesCrisis 答案中指出的无效语法。

你有几个小错误。

您可以通过查看您得到的每个编译错误并思考它的含义来解决它们。如果错误不清楚,您可以查看错误的行号,并思考可能导致它的原因。

请参阅工作代码:

int main()
{
    int i = -1;
    vector<vector<int> >N;
    vector<int>M;
    int temp;
    while (i++ != 5)
    {
        cin >> temp;
        M.push_back(temp);
    }
    N.push_back(M);
    return 0;
}