vector.push_back()与插入元素(例如vector [index])有什么区别?

发布于 2025-01-21 16:27:20 字数 948 浏览 2 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

梦冥 2025-01-28 16:27:20

当您创建向量时,您已经指定了一个大小(通常使用向量没有完成),因此您的向量已经填充了已设置为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; or vector<int>* ans = new vector<int>(); (if you want to create it on the heap) and then add a new element to it using ans.push_back(value); which will add the element to the back/end of the vector.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文