如何初始化本身具有重要构造函数的对象的 stl 向量?

发布于 2024-11-10 02:30:33 字数 1020 浏览 0 评论 0原文

假设我有以下类:

class MyInteger {
private:
  int n_;
public:
  MyInteger(int n) : n_(n) {};
  // MORE STUFF
};

并假设此类没有默认的简单构造函数 MyInteger()。由于某种原因,我必须始终提供一个 int 来初始化它。然后假设我的代码中的某个地方需要一个 vector。如何初始化此 vector 中的每个 MyInteger 组件?

我有两种情况(可能解决方案是相同的,但无论如何我都会说明它们),函数内的普通变量:

int main(){
    vector<MyInteger> foo(10);  //how do I initialize each 
                                //MyInteger field of this vector? 
    doStuff(foo);
}

以及作为类中的数据:

class MyFunClass {
private:
   vector<MyInteger> myVector;

public:
   MyFunClass(int size, int myIntegerValue) : myVector(size) {}; 
   // what do I put here if I need the 
   // initialization to call MyInteger(myIntegerValue) for all 
   // components of myVector?
};

是否可以仅在初始化列表中执行此操作,还是必须编写在 MyFunClass(int, int) 构造函数中手动初始化?

这看起来非常基本,但我不知何故在我的书中错过了它,并且在网上找不到。

suppose I have the following class:

class MyInteger {
private:
  int n_;
public:
  MyInteger(int n) : n_(n) {};
  // MORE STUFF
};

And suppose this class don't have a default trivial constructor MyInteger(). I must always supply an int to initialize it for some reason. And then suppose that somewhere in my code I need a vector<MyInteger>. How do I initialize each MyInteger component in this vector<>?

I have two situations (probably the solution is the same, but I'll state them anyway), a normal variable inside a function:

int main(){
    vector<MyInteger> foo(10);  //how do I initialize each 
                                //MyInteger field of this vector? 
    doStuff(foo);
}

and as data in a class:

class MyFunClass {
private:
   vector<MyInteger> myVector;

public:
   MyFunClass(int size, int myIntegerValue) : myVector(size) {}; 
   // what do I put here if I need the 
   // initialization to call MyInteger(myIntegerValue) for all 
   // components of myVector?
};

Is it possible to do it just in the initialization list or must I write the initialization by hand in the MyFunClass(int, int) constructor?

This seems so very basic, and yet I somehow missed it inmy book and can't find in the web.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(5

帅的被狗咬 2024-11-17 02:30:34

可以在不引用底层对象的情况下使用初始化列表。

#include <string>
#include <vector>
using namespace std;


class Test
{
   public:
   struct NumStr
   {
      int num;
      string str;
   };

   Test(vector<int> v1,vector<NumStr> v2) : _v1(v1),_v2(v2) {}
   vector<int> _v1;
   vector<NumStr> _v2;
};

int main()
{
   Test t={ {1,2,3}, {{1,"one"}, {2,"two"}, {3,"three"}} };
   cout << t._v1[1] << " " << t._v2[1].num << " " << t._v2[1].str << endl;
   return 0;
}

输出:2 2 2

Initialization lists can be used without reference to the underlying objects.

#include <string>
#include <vector>
using namespace std;


class Test
{
   public:
   struct NumStr
   {
      int num;
      string str;
   };

   Test(vector<int> v1,vector<NumStr> v2) : _v1(v1),_v2(v2) {}
   vector<int> _v1;
   vector<NumStr> _v2;
};

int main()
{
   Test t={ {1,2,3}, {{1,"one"}, {2,"two"}, {3,"three"}} };
   cout << t._v1[1] << " " << t._v2[1].num << " " << t._v2[1].str << endl;
   return 0;
}

output: 2 2 two

无敌元气妹 2024-11-17 02:30:33

有很多方法可以到达那里。以下是其中的一些(排名不分先后)。

使用 vector(size_type n, const T& t) 构造函数。它用 nt 副本初始化向量。例如:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values (10, MyInt (20))
    {
    }
};

将元素一一推入向量中。当值应该不同时这可能很有用。例如:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values ()
    {
        values.reserve (10); // Reserve memory not to allocate it 10 times...
        for (int i = 0; i < 10; ++i)
        {
            values.push_back (MyInt (i));
        }
    }
};

另一个选项是构造函数初始化列表,如果 C++0x 是一个选项:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values ({ MyInt (1), MyInt (2), MyInt (3) /* ... */})
    {
    }
};

当然,还有一个选项可以提供默认构造函数和/或使用 std::vector 之外的其他内容。

希望有帮助。

There are many ways to get there. Here are some of them (in no particular order of presence).

Use vector(size_type n, const T& t) constructor. It initializes vector with n copies of t. For example:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values (10, MyInt (20))
    {
    }
};

Push elements into vector one by one. This might be useful when values should be different. For example:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values ()
    {
        values.reserve (10); // Reserve memory not to allocate it 10 times...
        for (int i = 0; i < 10; ++i)
        {
            values.push_back (MyInt (i));
        }
    }
};

Another option is constructor initialization list, if C++0x is an option:

#include <vector>

struct MyInt
{
    int value;
    MyInt (int value) : value (value) {}
};

struct MyStuff
{
    std::vector<MyInt> values;

    MyStuff () : values ({ MyInt (1), MyInt (2), MyInt (3) /* ... */})
    {
    }
};

Of course, there is an option to provide default constructor and/or use something other than std::vector.

Hope it helps.

怪我太投入 2024-11-17 02:30:33

如果向量的元素不可默认构造,则无法使用向量执行某些操作。您不能这样写(示例 1):

vector<MyInteger> foo(10);

但是,您可以这样写(示例 2):

vector<MyInteger> foo(10, MyInteger(37));

(这只需要复制构造函数。)第二个参数是向量元素的初始值设定项。

在您的情况下,您还可以编写:

vector<MyInteger> foo(10, 37);

...因为 MyInteger 有一个以“int”作为参数的非显式构造函数。因此编译器会将 37 转换为 MyInteger(37) 并给出与示例 2 相同的结果。

您可能想研究 std::vector 文档

If the elements of the vector are not default-constructible, then there are certain things you cannot do with the vector. You cannot write this (example 1):

vector<MyInteger> foo(10);

You can, however, write this (example 2):

vector<MyInteger> foo(10, MyInteger(37));

(This only requires a copy constructor.) The second argument is an initializer for the elements of the vector.

In your case, you could also write:

vector<MyInteger> foo(10, 37);

...since MyInteger has a non-explicit constructor taking "int" as argument. So the compiler will cast 37 to MyInteger(37) and give the same result as example 2.

You might want to study the documentation on std::vector.

弃爱 2024-11-17 02:30:33
vector<MyInteger> foo(10, MyInteger(MY_INT_VALUE));

MyFunClass(int size, int myIntegerValue) : myVector(size, MyInteger(myIntegerValue)) {}; 
vector<MyInteger> foo(10, MyInteger(MY_INT_VALUE));

MyFunClass(int size, int myIntegerValue) : myVector(size, MyInteger(myIntegerValue)) {}; 
擦肩而过的背影 2024-11-17 02:30:33

除了很好地回答问题的所有答案之外,如果您的类 MyInteger 不可复制构造,您可以使用此技巧:而不是创建 vector<; MyInteger>,您可以创建vector<共享指针<我的整数> >

Besides all answers which answered the question very well, in a case that your class MyInteger is not copy-constructible, you could use this trick : instead of creating vector< MyInteger>, you could create vector< shared_ptr< MyInteger > >

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