初始化矢量的大小,否则附加不起作用,为什么

Initialize the size of vector else appending wont work, why?

本文关键字:不起作用 为什么 初始化      更新时间:2023-10-16
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
using namespace std;
int main()
{
int n;
vector < string > arr(100); // initialise the size of vector always else 
appending wont work,why?
string y;
int x;
cin>>n;
for(int i=0;i<n;i++)
{
    cin>>x>>y;
    fflush(stdin);
    if(i<n/2)
    {
       arr[x].append("- "); //appending the first 10 positions with "- "
    }
    else
    {
        arr[x].append(y);
        arr[x].append(" "); //appending the last 10 positions with given 
strings
    }
}
for(int i=0;i<100;i++)
{
    cout<<arr[i];
}
return 0;
} 

使用 + 或附加附加都不起作用,它会发出警告,请解释为什么先生?它发出警告,指向算术运算中使用的函数的指针...

初始化矢量的大小总是否则附加不起作用,为什么?

因为这段代码:

arr[x].append("- ");

表示"在向量arr的第 x 个元素上调用方法append()"。当您创建arr空的第 x 个元素(无论x具有什么值(不存在,并且您的代码具有 UB。