C++ push_back 一个向量到另一个向量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8411994/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
push_back a vector into another vector
提问by Yucoat
I want to push_back()
a vector M
into vector N
.
我想将push_back()
一个 vectorM
转化为 vector 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;
}
Compilation error
编译错误
I get a syntax error.
我收到语法错误。
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$
采纳答案by juanchopanza
You need
你需要
M.push_back(temp);
in the while loop, besides the invalid syntax pointed out in @StilesCrisis' answer.
在 while 循环中,除了@StilesCrisis 的回答中指出的无效语法之外。
回答by StilesCrisis
This line
这条线
N.push_back(vector<int>M);
should be
应该
N.push_back(M);
Also
还
vector<vector<int> >N,
should be
应该
vector<vector<int> >N;
回答by Igor Oks
You have few minor mistakes.
你有几个小错误。
You could solve them by looking on each of the compilation errors you got, and thinking what it means. If the error is not clear, you can look at the error's line number, and think what could cause it.
您可以通过查看您遇到的每个编译错误并思考其含义来解决它们。如果错误不清楚,您可以查看错误的行号,并思考可能导致它的原因。
See the working code:
查看工作代码:
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;
}
回答by Scott
N.insert(N.end(),M.begin(),M.end());