为什么这会在Visual Studio 2012中编译,而不是UNIX

Why Will This Compile in Visual Studio 2012 But Not UNIX?

本文关键字:编译 UNIX 2012 Visual Studio 为什么      更新时间:2023-10-16
#include <iostream>
#include <cstdlib>
#include <string>
#include <ctype.h>
#include <cmath>
#include <functional>
#include <numeric>
#include <algorithm>
using namespace std;
int main(int argc, char *argv[])
{
int length = 0;
cout << "Enter a string: ";
string buffer;
char buff[1024];
while (getline(cin, buffer)) 
{
    buffer.erase(remove_if(buffer.begin(), buffer.end(), not1(ptr_fun(isalnum))), buffer.end());
    break;
}
length = buffer.length();
int squareNum = ceil(sqrt(length));
strcpy(buff, buffer.c_str());
char** block = new char*[squareNum];
for(int i = 0; i < squareNum; ++i)
block[i] = new char[squareNum];
int count = 0 ;
for (int i = 0 ; i < squareNum ; i++)
{
    for (int j = 0 ; j < squareNum ; j++)
    {
        block[i][j] = buff[count++];
    }
}
for (int i = 0 ; i < squareNum ; i++)
{
    for (int j = 0 ; j < squareNum ; j++)
    {
        cout.put(block[j][i]) ;
    }
}
return 0;
}

错误:

asst4.cpp: 在函数 'int main(int, char**)' 中:asst4.cpp:30:76:错误:调用"ptr_fun()"没有匹配函数ASST4.cpp:30:76:注意:候选人是:/usr/include/c++/4.6/bits/stl_function.h:443:5: 注意:模板 std::p ointer_to_unary_function std::p tr_fun(_Result (*)(_Arg))/usr/include/c++/4.6/bits/stl_function.h:469:5:注意:模板 std::p ointer_to_binary_function std::p tr_fun(_Result (*)(_Arg1, _Arg2))asst4.cpp:37:29:错误:"strcpy"未在此范围内声明
std::strcpy

cstring标题中,应该包括在内。

std::isalnum也在locale标题中,std::ptr_fun无法选择您需要的标头。您应该像

std::not1(std::ptr_fun<int, int>(std::isalnum))

或将std::isalnum转换为所需的签名

std::not1(std::ptr_fun(static_cast<int(*)(int)>(std::isalnum)))

对于strcpy问题,请使用例如 std::copy,或包含包含strcpy原型的<cstring>

并不是说你真的需要那个临时的buff变量,因为你可以使用例如 buffer[count++]也是。

strcpy错误很明显——只是#include <cstring>

对于ptr_fun()错误,我的猜测是您的using namespace std导致它尝试使用<locale>标头中std::isalnum的模板化版本之一。只需将调用更改为

not1(ptr_fun(::isalnum))

使它在我的系统上与 G++ 和 clang 一起愉快地编译。