Часто используемые фрагменты: различия между версиями
Перейти к навигации
Перейти к поиску
Ctrlalt (обсуждение | вклад) Нет описания правки |
Ctrlalt (обсуждение | вклад) |
||
| Строка 75: | Строка 75: | ||
return res; | return res; | ||
} | } | ||
| width="10px" | | | width="10px" | | ||
| width=50% | | | width=50% | | ||
Версия от 06:39, 9 марта 2023
Split и join
vector<string> split(string &line) {
vector<string> words;
string word;
for (char c : line) {
if (c != ' ') {
word += c;
} else if (!word.empty()) {
words.push_back(word);
word.clear();
}
}
if (!word.empty())
words.push_back(word);
return words;
}
|
string join(vector<string> &words) {
string line;
for (int i = 0; i < words.size(); i++)
line += words[i] + (i + 1 < words.size() ? " " : "");
return line;
}
|
vector<string> split(string &line, const string &separators) {
vector<string> words;
string word;
for (char c : line) {
if (separators.find(c) == -1) {
word += c;
} else if (!word.empty()) {
words.push_back(word);
word.clear();
}
}
if (!word.empty())
words.push_back(word);
return words;
}
|
string join(vector<string> &words, const string &separator) {
string line;
for (int i = 0; i < words.size(); i++)
line += words[i] + (i + 1 < words.size() ? separator : "");
return line;
}
|
Перевод систем счисления
long long toDec(string s, int base) {
static const string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
long long res = 0;
for (char c : s)
res = res * base + DIGITS.find(c);
return res;
}
|
string fromDec(long long n, int base) {
static const string DIGITS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
string res;
while (n >= base) {
res += DIGITS[n % base];
n /= base;
}
res += DIGITS[n];
reverse(res.begin(), res.end());
return res;
}
|
Римская система счисления
string toRoman(int n) {
static const vector<pair<string, int>> CODES = {
{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400},
{"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40},
{"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}
};
string res;
for (auto &[code, value] : CODES) {
while (n >= value) {
n -= value;
res += code;
}
}
return res;
}
|
int fromRoman(string &s) {
static const vector<pair<string, int>> CODES = {
{"M", 1000}, {"CM", 900}, {"D", 500}, {"CD", 400},
{"C", 100}, {"XC", 90}, {"L", 50}, {"XL", 40},
{"X", 10}, {"IX", 9}, {"V", 5}, {"IV", 4}, {"I", 1}
};
int pos = 0, res = 0;
for (auto &[code, value] : CODES) {
while (s.substr(pos, code.size()) == code) {
pos += code.size();
res += value;
}
}
return res;
}
|