我在同一个项目中有两个文件,分别是f1.cpp
和f2.cpp
,用于解决算法中相同的“连通性问题”。在 visual studio 中,我将它们放入源文件中。源文件中的另一个文件是 pch.cpp
。项目名称也是 f1
。
f1.cpp的代码是,
#include "pch.h"
#include <iostream>
using namespace std;
static const int N = 10000;
int main()
{
int i, p, q, id[N];
for (i = 0; i < N; i++) id[i] = i;
while (cin >> p >> q) {
int t = id[p];
if (t == id[q]) continue;
for (i = 0; i < N; i++)
// this is for union
if (id[i] == t) id[i] = id[q];
cout << " " << p << " " << q << endl;
}
std::cout << "Hello World!\n";
return 0;
}
f2.cpp 是,
#include <iostream>
#include "pch.h"
using namespace std;
static const int N = 10000;
int main() {
int i, j, p, q, id[N], sz[N];
for (i = 0; i < N; i++) { id[i] = i, sz[i] = 1; }
while (cin >> p >> q) {
for (i = p; i != id[i]; i = id[i]);
for (j = q; j != id[j]; j = id[j]);
if (i == j) continue;
if (sz[i] < sz[j]) {
id[i] = j; sz[j] += sz[i];
}
else {
id[j] = i; sz[i] += sz[j];
}
cout << " " << p << " " << q << endl;
}
}
虽然我很确定这两个代码,如果独立运行,是没有错误的。但是当它们一起出现在源文件中时,当我运行 f2.cpp 时,会出现错误
C2065 'cin': undeclared identifier connectivity problem
C2065 'cout': undeclared identifier connectivity problem
C2065 'endl': undeclared identifier connectivity problem
My question is why the error like this happens ?
Do I have to open a new project in visual studio for editing different solutions on same problems ?
最佳答案
就像我之前指出的那样,如果同时运行多个源文件,链接器将生成两个 main()
方法,这将导致编译器错误,因为您只能有一个 主()
...
记住程序只能指向一个main()
函数...
但是,您可以在代码中使用#define
:
#include "pch.h"
#include <iostream>
using namespace std;
static const int N = 10000;
// Running the first project...
#define F_PROJ
// Psuedo main for first project...
int first_main()
{
int i, p, q, id[N];
for (i = 0; i < N; i++) id[i] = i;
while (cin >> p >> q) {
int t = id[p];
if (t == id[q]) continue;
for (i = 0; i < N; i++)
// this is for union
if (id[i] == t) id[i] = id[q];
cout << " " << p << " " << q << endl;
}
std::cout << "Hello World!\n";
return 0;
}
// Psuedo main for second project...
int second_main()
{
int i, j, p, q, id[N], sz[N];
for (i = 0; i < N; i++) { id[i] = i, sz[i] = 1; }
while (cin >> p >> q) {
for (i = p; i != id[i]; i = id[i]);
for (j = q; j != id[j]; j = id[j]);
if (i == j) continue;
if (sz[i] < sz[j]) {
id[i] = j; sz[j] += sz[i];
}
else {
id[j] = i; sz[i] += sz[j];
}
cout << " " << p << " " << q << endl;
}
return 0;
}
int main()
{
#ifdef F_PROJ
first_main();
#elif defined(S_PROJ)
second_main();
#endif
}
只需分别点#define F_PROJ
或#define S_PROJ
...
关于Visual Studio中的C++运行结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235696/