英文:
merge the two vectors
问题
Here is the translated code portion:
我们需要合并这两个向量,我正在尝试这样做,但是我没有从给定的代码中得到输出...请帮助我找出问题所在。
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v1={1,2,4,5};
vector<int> v2={10,9,6,3};
vector<int> v3;
int i=0;
for(int value1:v1)
{
v3[i]=value1;
i++;
}
for(int value2:v2)
{
v3[i]=value2;
i++;
}
for(int value3:v3)
{
cout<<value3<<" ";
}
}
If you have any further questions or need assistance with this code, please let me know.
英文:
we have to merge the two vector and i am do so but i do not get the output from the give code ...please help me to find out the problem..
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int> v1={1,2,4,5};
vector<int> v2={10,9,6,3};
vector<int> v3;
int i=0;
for(int value1:v1)
{
v3[i]=value1;
i++;
}
for(int value2:v2)
{
v3[i]=value2;
i++;
}
for(int value3:v3)
{
cout<<value3<<" ";
}
}
a correct code for my question
答案1
得分: 4
v3
为空,所以v3[i]=...;
越界了。你需要使用v3.push_back(value)
或v3.emplace_back(value)
来添加元素。示例:
std::vector<int> v3;
v3.reserve(v1.size() + v2.size());
for(int value : v1) {
v3.push_back(value);
}
for(int value : v2) {
v3.push_back(value);
}
更简单的方法是从v1
复制构造v3
,然后使用成员函数insert
一次性将所有元素从v2
添加到v3
的末尾:
std::vector<int> v3 = v1;
v3.insert(v3.end(), v2.begin(), v2.end());
英文:
v3
is empty so v3[i]=...;
is out of bounds. You need v3.push_back(value)
or v3.emplace_back(value)
to add elements to it. Example:
std::vector<int> v3;
v3.reserve(v1.size() + v2.size());
for(int value : v1) {
v3.push_back(value);
}
for(int value : v2) {
v3.push_back(value);
}
A simpler way would be to copy construct v3
from v1
and then use the member function insert
to add all the elements from v2
at the end of v3
at once:
std::vector<int> v3 = v1;
v3.insert(v3.end(), v2.begin(), v2.end());
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论