英文:
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 <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);
}
}
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<A>(3);
or if you have a particular value in mind
A y = something;
B.x = std::vector<A>(3, y);
Maybe this code should be in the constructor for B
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论