vector.push_back()与插入元素(例如vector [index])有什么区别?
class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int n=nums.size();
vector<int> ans(2*n);
for(int i=0;i<2*n;i++)
{
if(i<n)
{
ans.push_back(nums[i]);
}
else
{
ans.push_back(nums[i-n]);
}
}
return ans;
}
};
以上代码没有提供适当的ANS。
下面的代码正常工作。
class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int n=nums.size();
vector<int> ans(2*n);
for(int i=0;i<2*n;i++)
{
if(i<n)
{
ans[i]=nums[i];
}
else
{
ans[i]=nums[i-n];
}
}
return ans;
}
};
class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int n=nums.size();
vector<int> ans(2*n);
for(int i=0;i<2*n;i++)
{
if(i<n)
{
ans.push_back(nums[i]);
}
else
{
ans.push_back(nums[i-n]);
}
}
return ans;
}
};
This above code is not giving appropriate ans.
while below code is working fine.
class Solution {
public:
vector<int> getConcatenation(vector<int>& nums) {
int n=nums.size();
vector<int> ans(2*n);
for(int i=0;i<2*n;i++)
{
if(i<n)
{
ans[i]=nums[i];
}
else
{
ans[i]=nums[i-n];
}
}
return ans;
}
};
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您创建向量时,您已经指定了一个大小(通常使用向量没有完成),因此您的向量已经填充了已设置为0的INT。因此,当您使用
ans [i] [i] = nums [i]; << /code>您只是在编辑向量中存储的已经存在的元素之一。
通常,当您创建向量时,您会通过执行
vector&lt; int&gt;创建它作为空的。 ans;
或vector&lt; int&gt;* ans = new vector&lt; int&gt;();
(如果您想在堆上创建它),然后使用<<<代码> ans.push_back(value); 将将元素添加到向量的背面/结尾。When you create the vector you have specified a size already (usually not done with vectors) so your vector already filled with ints that have been set to 0. So when you use
ans[i] = nums[i];
you are simply editing one of the already existing elements stored in the vector.Usually when you create a vector you create it as an empty one by doing
vector<int> ans;
orvector<int>* ans = new vector<int>();
(if you want to create it on the heap) and then add a new element to it usingans.push_back(value);
which will add the element to the back/end of the vector.