【问题标题】:push_back a vector into another vectorpush_back 一个向量到另一个向量
【发布时间】:2011-12-07 07:51:50
【问题描述】:

我想将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$ 

【问题讨论】:

  • 让我们为新社区成员提供改进建议。我同意,错误消息很有帮助。
  • @Nicol:Yucoat 已更新问题以包含错误消息。 :)

标签: c++ stl vector


【解决方案1】:

这一行

N.push_back(vector<int>M);

应该是

N.push_back(M);

还有

vector<vector<int> >N,

应该是

vector<vector<int> >N;

【讨论】:

  • 我听从了您的建议并更改了我的代码,但 g++ 仍然不接受
  • @Yucoat 你试过理解g++给你的错误信息吗?它应该告诉您while 中存在错误
【解决方案2】:
N.insert(N.end(),M.begin(),M.end());

【讨论】:

  • 虽然此代码可能有助于解决问题,但提供有关 why 和/或 如何 回答问题的附加上下文将显着改善长期价值。请edit你的答案添加一些解释。
【解决方案3】:

你需要

M.push_back(temp);

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

【讨论】:

    【解决方案4】:

    你有几个小错误。

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

    查看工作代码:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 2016-08-18
      相关资源
      最近更新 更多