改进 C++ 向量插入(初始)编写

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

better cpp vector insert(initial) writing

问题

我正在尝试在另一个实例中初始化一个已定义类的向量,测试代码如下:

```cpp
#include <vector>

class A
{
public:
    float x = 0.0;
};

class B
{
public:
    std::vector<A> b;
};

int main()
{
    B x;
    for (int i = 0; i < 3; i++)
    {
        A y;
        x.b.insert(x.b.begin(), y);
    }
}

但是否有更巧妙的方法来初始化x?也许像这样:

x.b.insert(x.b.begin(), 3, A);
但我得到错误error: expected primary-expression before ‘)’ token
谢谢


<details>
<summary>英文:</summary>

i am trying to initial a vector of a defined class in another instance, the test code is as:

```cpp
#include &lt;vector&gt;

class A
{
public:
    float x = 0.0;
};

class B
{
public:
    std::vector&lt;A&gt; b;
};

int main()
{
    B x;
    for(int i = 0; i &lt; 3; i++)
    {
        A y;
        x.b.insert(x.b.begin(), y);
    }
       
}

but is there a more brilliant writing for the initial of x?
something maybe like

x.b.insert(x.b.begin(), 3, A);
which i got error error: expected primary-expression before ‘)’ token
thx

edit: sorry, edited for a better example

答案1

得分: 1

不需要循环或insert,只需构造向量并赋值

B.x = std::vector<A>(3);

或者如果你有特定的值

A y = something;
B.x = std::vector<A>(3, y);

也许这段代码应该放在B的构造函数中。

英文:

No need for a loop or insert, just construct the vector and assign it

B.x = std::vector&lt;A&gt;(3);

or if you have a particular value in mind

A y = something;
B.x = std::vector&lt;A&gt;(3, y);

Maybe this code should be in the constructor for B.

huangapple
  • 本文由 发表于 2023年2月16日 19:34:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/75471677.html
匿名

发表评论

匿名网友

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

确定