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

8
我想把向量M使用push_back()函数加入到向量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$ 

2
让我们对新社区成员提出温和的改进建议。我同意,错误信息很有帮助。 - Codie CodeMonkey
@Nicol:Yucoat已经更新了问题,包括错误信息。 :) - sarnold
4个回答

8
N.insert(N.end(),M.begin(),M.end());

6
虽然这段代码可能有助于解决问题,但提供关于为什么和/或如何回答问题的额外上下文信息将显著提高其长期价值。请[编辑]您的答案添加一些解释。 - Toby Speight

5

这一行

N.push_back(vector<int>M);

应该是

N.push_back(M);

此外

vector<vector<int> >N,

应该是

vector<vector<int> >N;

1
我按照你的建议修改了我的代码,但是g++仍然不接受。 - Yucoat
@Yucoat 你尝试理解g++给出的错误信息了吗?它应该告诉你在你的while循环内部有一个错误。 - Pablo

3

你需要

M.push_back(temp);

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

3

您有一些小错误。

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

请参考以下可正常工作的代码:

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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接