矩阵乘法
vector库创造二维数组,三层循环加公式解决矩阵C
#include<iostream>
#include<vector>
using namespace std;
int main() {
int n, m, k;
cin >> n >> m >> k;
vector<vector<int>>A(n, vector<int>(m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> A[i][j];
}
}
vector<vector<int>>B(m, vector<int>(k));
for (int i = 0; i < m; i++) {
for (int j = 0; j < k; j++) {
cin >> B[i][j];
}
}
vector<vector<int>>C(n, vector<int>(k));
for (int i = 0; i < n; i++) {
for (int j = 0; j < k; j++) {
for (int q = 0; q < m; q++) {
C[i][j] += A[i][q] * B[q][j];
}
cout << C[i][j] << " ";
}
cout << endl;
}
return 0;
}
句子反转
利用vector库和stringstream进行预处理,用迭代器将句子解为单词
再进行判断并操作,最后insert进行整体翻转
#include<iostream>
#include<sstream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
string input;
vector<string>result= {};
getline(cin, input);
stringstream sentence(input);
vector<string> word(istream_iterator<string>{sentence}, istream_iterator<string>());
for (string& a : word) {
for (char& character : a) {
if (isupper(character)) {
character = tolower(character);
}
if (islower(character)) {
character = toupper(character);
}
if (isdigit(character)) {
reverse(a.begin(), a.end());
}
}
result.insert(result.begin(), a);
}
for (string c : result) {
cout << c << " ";
}
}
华小科的旅行
继续用vector做二维数组,注意行数列数与位置序号的区别
#include<iostream>
#include<vector>
using namespace std;
int main() {
int m, n, x, y;
cin >> m >> n >> x >> y;
vector<vector<int>>data(n, vector<int>(2*m));
for (int i = 0; i < n; i++) {
for (int j = 0; j < 2*m; j++) {
cin >> data[i][j];
}
}
cout << x << " " << y << endl;
while (x != 0||y !=0) {
int memory = x;
x = data[x-1][2 * y - 2];
y = data[memory-1][2 * y-1];
if (x != 0 || y != 0) {
cout << x << " " << y << endl;
}
}
}
排序
黑马程序员讲过的multiset可以很好解决这个问题,与set不同,它允许重复元素,符合题意
#include<iostream>
#include<set>
using namespace std;
int main() {
int num;
cin >> num;
multiset<int>data;
for (int i = 0; i < num; i++) {
int memory;
cin >> memory;
data.insert(memory);
}
for (int a : data) {
cout << a << " ";
}
cout << endl;
}