我可以在不推送向量的情况下向向量添加值吗?

Can I add a value to a vector without pushing it?

本文关键字:向量 添加 情况下 我可以      更新时间:2023-10-16

有什么方法可以创建这样的向量对

  std::vector<std::pair<std::string, int>> myReg;

然后像这样添加它:

  myReg[0].first = "title of the movie";
  myReg[0].second = 1968;
  myReg[1].first = "title of the 2nd movie";
  myReg[1].second = 2008;

因为它给了我一个

调试断言失败

不使用这个:

myReg.push_back(std::pair<std::string, int>("title of the movie", 1968));

使用初始值设定项列表:

std::vector<std::pair<std::string, int>> myReg{
    {"title of the movie", 1968},
    {"title of the 2nd movie", 2008}
};

如果您稍后需要添加更多内容,它仍然很简单:

myReg.push_back({"title 3", 2000});
myReg.emplace_back("title 4", 2001);

对于您显示的确切代码片段,您必须首先执行以下操作myReg.resize(2)

std::vector<std::pair<std::string, int>> myReg;
myReg.resize(2);
myReg[0].first = "title of the movie";

您也可以将std::vector<...> myReg;更改为myReg(2);

std::vector<std::pair<std::string, int>> myReg(2);
myReg[0].first = "title of the movie";

正如评论中提到的,另一种选择是使用std::map<>而不是vector<>;这给了你"自动扩展"(不调用push_back()(,但通常不如vector<>方便,因为内存不是连续的。 该代码看起来像

std::map<int, std::pair<std::string, int>> myReg;
myReg[0].first = "title of the movie";

你也可以用一个operator [](和at()(制作自己的类似向量的类来自动增长向量;这很快就会变得混乱,并且可能会被你的同事皱眉,但这里有一个(不一定推荐(的想法:

template<typename T>
class my_vector
{
    std::vector<T> v;
public:
    T& operator[](size_t i) {
        if (i >= v.size())
            v.resize(i+1);
        return v[i];
    }
    // ... a lot of other methods copied from std::vector<> ...
};
my_vector<std::pair<std::string, int>> myReg;
myReg[0].first = "title of the movie";

您有 2 种常规方法:

首先,您可以使用 vector 的构造函数:


载体(initializer_list IL, const allocator_type& alloc = allocator_type(((;

std::vector<std::pair<std::string, int>> myReg(2);
myReg[0].first = "title of the movie";
myReg[0].second = 1968;
myReg[1].first = "title of the 2nd movie";
myReg[1].second = 2008;

显式向量 (size_type n, const value_type& val = value_type((, const allocator_type& alloc = allocator_type(((;

std::vector<std::pair<std::string, int>> myReg{
    {"title of the movie", 1968},
    {"title of the 2nd movie", 2008}
};

或者在启动前调整向量的大小:

std::vector<std::pair<std::string, int>> myReg;
myReg.resize(2)
myReg[0].first = "title of the movie";
myReg[0].second = 1968;
myReg[1].first = "title of the 2nd movie";
myReg[1].second = 2008;

感谢大家的帮助。很棒的人,有很多想法。

好的,这是从@Dan作为一个选项,尽管我正在研究可能使用类或@chris的方法

  std::vector<std::pair<std::string, int>> myReg(1);
  myReg[0].first = "title of the movie";
  myReg[0].second = 1968;
  myReg.resize(2);
  myReg[1].first = "title of the 2nd movie";
  myReg[1].second = 2008;