Reputation: 1267
#include <bits/stdc++.h>
using namespace std;
int main (){
ios_base::sync_with_stdio(false);
cin.tie(NULL);
vector <int> a;
string str;
cin>>str;
for(int i = 0; i < str.size(); i++){
if(str[i]!='+')
{
int c = str[i]-'0';
a.push_back(c);
}
}
sort(a.begin(), a.end());
cout<<a.at(0);
for(int j = 1; j < str.size(); j++){
cout<<'+'<<a.at(j);
}
return 0;
}
Upvotes: 1
Views: 91
Reputation: 21510
You need to change the stop condition of the loop to be stopping on the size of the vector and not the string. So change your last loop to the following
for(int j = 1; j < a.size(); j++){
cout<<'+'<<a.at(j);
}
Further if you want to print all the values in the format you specified you would want to do the following
assert(!a.empty());
for(int j = 0; j < a.size() - 1; j++){
cout << a.at(j) << '+';
}
cout << a.back() << endl;
One last thing about your implementation. If you are always going to be given a string of the format "a+b+c+d" you do not need a vector to reverse the sequence and print. You can simply do the following
std::reverse(str.begin(), str.end()); // #include <algorithm>
And then the string will have the sequence you want. If you do not want to do it in place and need another container you could do
// #include <iterator> and #include <algorithm>
string other_string;
std::copy(str.crbegin(), str.crend(), std::back_inserter(other_string));
^ This will copy the string in reversed order to another string object.
Upvotes: 1