jeudi 26 mars 2020

std::swap on strings returning undefined behavior

On running any test case for instance 7 5 1. (t=7, n=5, k=1) following code returns an empty string, something goes wrong with both the swaps, I am unable to figure out what. Kindly help.

int temp=2;
    vector <int> x;
    x.push_back(0);
    for(int i=1;i<100005;i++)
    {
            x.push_back(x[i-1]+temp);
            temp++;
    }
    while(t--)
    {
            char temp;
            cin>>n>>k;
            string str(n-2,'a'), str1="bb";
            str=str+str1;
            cout<<"Initial "<<str.length()<<endl;
            std::vector<int>::iterator low1;
            low1=upper_bound(x.begin(),x.end(),k); //Only commenting out this, still string is empty
            cout<<*low1<<" "<<low1-x.begin()<<endl;
            swap(str[low1-x.begin()], str[1]);
            k=k-(*low1);
            swap(str[0],str[k-1]);
            cout<<"Final"<<endl;
            cout<<str<<endl; //This is empty (Somehow undefined behavior);
    }

Aucun commentaire:

Enregistrer un commentaire