合并这两个向量。

huangapple go评论68阅读模式
英文:

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&lt;iostream&gt;
#include&lt;vector&gt;
using namespace std;
int main()
{
  vector&lt;int&gt; v1={1,2,4,5};
  vector&lt;int&gt; v2={10,9,6,3};
   vector&lt;int&gt; 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&lt;&lt;value3&lt;&lt;&quot; &quot;;
        }
        
}

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&lt;int&gt; 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&lt;int&gt; v3 = v1;
v3.insert(v3.end(), v2.begin(), v2.end());

Demo

huangapple
  • 本文由 发表于 2023年6月12日 04:29:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452402.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定