1.leetcode对象实例化解题示例(lc_No.217)
如下图所示为leetcode一道题目描述
在leetcode上的代码解答如下
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i = 0; i < n - 1; i++) {
if (nums[i] == nums[i + 1]) {
return true;
}
}
return false;
}
};
由于其网页内嵌的编译器包含了类实例化及函数调用的部分,因而刷题的时候我们可能会忽略到较为重要的隐藏部分的数据结构转换以及调用,因而我在VS上编写了类定义、头文件索引和对象实例化的代码如下
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
class Solution {
public:
bool containsDuplicate(vector<int>& nums) {
sort(nums.begin(), nums.end());
int n = nums.size();
for (int i = 0; i < n - 1; i++) {
if (nums[i] == nums[i + 1]) {
return true;
}
}
return false;
}
};
int main()
{
Solution theSolution;
vector<int> num;
int temp[] = { 1, 2, 3, 4, 1 };
for (int i = 0; i < sizeof(temp)/sizeof(temp[0]); i++)
{
num.push_back(temp[i]);
cout << num[i] << endl;
}
bool res = theSolution.containsDuplicate(num);
cout << res << endl;
return 0;
}
#include <iostream>
#include <time.h>
using namespace std;
struct ListNode
{
int value;
ListNode* next;
ListNode(): value(0), next(nullptr){}
ListNode(int _value): value(_value), next(nullptr){}
ListNode(int _value, ListNode *_next): value(_value), next(_next){}
};
ListNode *CreateListNode(int a[]) {
ListNode *L, *cur, *p;
L = new ListNode();
cur = L;
L->next = nullptr;
int i = 0;
while (a[i] != '\0') {
p = new ListNode();
p->value = a[i];
cur->next = p;
cur = p;
++i;
}
cur->next = nullptr;
return L;
}
int main() {
int x[1024] = { 1, 2, 3, 4, 5, 6 };
ListNode *p;
ListNode *L = CreateListNode(x);
p = L->next;
while (p != nullptr) {
printf("%d\n", p->value);
p = p->next;
}
system("pause");
return 0;
}
一个使用OpenMP的“hello, world”程序
#include <iostream>
#include <omp.h>
void Hello() {
int my_rank = omp_get_thread_num();
int thread_count = omp_get_num_threads();
printf("Hello from thread %d of %d\n", my_rank, thread_count);
}
int main() {
int thread_count;
std::cin >> thread_count;
# pragma omp parallel num_threads(thread_count)
Hello();
return 0;
}
其输入输出为
4
Hello from thread 0 of 4
Hello from thread 2 of 4
Hello from thread 3 of 4
Hello from thread 1 of 4