#include<bits/stdc++.h> using namespace std; int main(){ string s; getline(cin,s); stringstream ss(s); string str; vector<string> nums; while(getline(ss,str,',')){ nums.push_back(str); } int m; cin>>m; vector<int> line; vector<vector<int>> lines; string strr; int len = nums.size(); for(int i=0; i<len; i++){ line.clear(); stringstream ss2(nums[i]); while(getline(ss2,strr,'-')){ line.push_back(stoi(strr)); } lines.push_back(line); } sort(lines.begin(), lines.end(), [](const vector<int>& a, const vector<int>& b){ return a[0] < b[0]; }); string ans1, ans2; for(auto& line : lines){ if(line.size() == 1){ if(line[0] == m){ nums.erase(remove(nums.begin(), nums.end(), to_string(line[0])), nums.end()); } } else if(line.size() == 2){ int l = line[0]; int r = line[1]; if(l < m && m < r){ ans1 = to_string(l) + "-" + to_string(m - 1); ans2 = to_string(m + 1) + "-" + to_string(r); if(l == m - 1){ ans1 = to_string(l); } else if(r == m + 1){ ans2 = to_string(r); } } } } if(!ans1.empty()){ nums.push_back(ans1); } if(!ans2.empty()){ nums.push_back(ans2); } for(int i=0; i<nums.size(); i++){ cout << nums[i]; if(i != nums.size() - 1){ cout << ","; } } return 0; }输入1-5 2如何在输出结果中删除1-5
时间: 2024-04-16 12:29:01 浏览: 27
要在输出结果中删除1-5,你可以在遍历`lines`的过程中,将包含1-5的元素从`nums`中删除。可以使用`erase`和`remove`函数来实现这个过程。具体的代码实现可以参考以下示例:
```cpp
#include<bits/stdc++.h>
using namespace std;
int main(){
string s;
getline(cin,s);
stringstream ss(s);
string str;
vector<string> nums;
while(getline(ss,str,',')){
nums.push_back(str);
}
int m;
cin>>m;
vector<int> line;
vector<vector<int>> lines;
string strr;
int len = nums.size();
for(int i=0; i<len; i++){
line.clear();
stringstream ss2(nums[i]);
while(getline(ss2,strr,'-')){
line.push_back(stoi(strr));
}
lines.push_back(line);
}
sort(lines.begin(), lines.end(), [](const vector<int>& a, const vector<int>& b){
return a[0] < b[0];
});
string ans1, ans2;
for(auto& line : lines){
if(line.size() == 1){
if(line[0] == m){
nums.erase(remove(nums.begin(), nums.end(), to_string(line[0])), nums.end());
}
} else if(line.size() == 2){
int l = line[0];
int r = line[1];
if(l < m && m < r){
ans1 = to_string(l) + "-" + to_string(m - 1);
ans2 = to_string(m + 1) + "-" + to_string(r);
if(l == m - 1){
ans1 = to_string(l);
} else if(r == m + 1){
ans2 = to_string(r);
}
}
}
}
if(!ans1.empty()){
nums.push_back(ans1);
}
if(!ans2.empty()){
nums.push_back(ans2);
}
// 删除包含1-5的元素
nums.erase(remove_if(nums.begin(), nums.end(), [](const string& num){
return num == "1-5";
}), nums.end());
for(int i=0; i<nums.size(); i++){
cout << nums[i];
if(i != nums.size() - 1){
cout << ",";
}
}
return 0;
}
```
在上面的代码中,通过使用`nums.erase`和`remove_if`函数,我们从`nums`中删除了包含"1-5"的元素。最后,输出结果将不再包含1-5。