Search code examples
c++14stdvectorstdstring

Conversion of std::string indices to integer in a std::vector


I want to access the last two index of std::string in a std::vector and then converting them to integer.But somehow I can not access it.Is there any optimal way for that?Thanks in advance

eg:say if the string is 6513494.Then the expected output for vector[i]will be 9 and 4

int n;string s;cin>>n;
vector<string>v;
for(int i=0;i<n;++i)
{
    cin>>s;v.push_back(s);
}
for(int i=0;i<v.size();++i)if(v[s[s.size()-1]]-'0'==0&&v[s[s.size()-2]]-'0')cout<<v[i]<<endl;

Solution

  • Try this, I believe it will help with what you wanted :)

        int n, val, ln;
        string s;
        cin>>n;
        vector<int>v;
    
        for(int i=0;i<n;++i)
        {
            cin>>s;
            ln = s.size();
            val = (s[ln-2]-'0') * 10 + (s[ln-1]-'0');
            v.push_back(val);
        }
    
        for(int i=0;i<v.size();++i){
            printf("%d\n", v[i]);
        }