【问题标题】:Passing values to Pair in C++在 C++ 中将值传递给 Pair
【发布时间】:2015-04-01 12:10:32
【问题描述】:

我有一对类型为String 和String &,我可以将值传递给Pair,如下所示

typedef std::pair<std::string, std::string&> NamedNode;
voi main(){
std::string name = "name";
std::string * value = new std::string("value") ;
NamedNode(name,*value);}

当我将值传递给 Pair 时,如上所示,出现以下错误:

错误 C2529: '_Val2' : 对引用的引用是非法的 c:\program files (x86)\microsoft visual studio 9.0\vc\include\utility

error C2665: 'std::pair<_ty1>::pair' : 3 个重载都不能转换所有参数类型 d:\jzon\sample.cpp

及以下警告:

警告 1 警告 C4181:限定符应用于引用类型;忽略 c:\program files (x86)\microsoft visual studio 9.0\vc\include\utility

我使用的是 C++98,Microsoft Visual Studio 2008,OS-windows XP

【问题讨论】:

  • 你的编译器是怎么说的?剧透:答案是否定的。
  • 您正在传递一个指向引用变量的指针,所以没有。也使用int main() 而不是void main()
  • 如果你尝试编译它,你就会知道答案。

标签: c++ stl


【解决方案1】:

不,是*value。

  • 当对命令行参数不感兴趣时​​,C++ 中的标准 main 是 int main(),当需要处理参数时,标准 main 是 int main(int argc, char* argv[]) 或 int main(int argc, char** argv)。

代码(在 GCC 4.9.1 中使用 C++11 测试):

#include <utility>
#include <iostream>
#include <string>

typedef std::pair<std::string, std::string&> NamedNode;
int main() {
    std::string name = "name";
    std::string* value = new std::string("value");
    NamedNode a(name, *value);
    std::cout << a.first << " " << a.second << std::endl;
    return 0;
}

&amp; 运算符的意思是 reference of 在这种情况下 std::string 你需要传递一个 std::string 而不是 std::string*

提示:不要在C++ 中使用 new,几乎可以肯定不需要并且允许不良做法(例如:抛出异常时的内存泄漏等),请改用 std ::unique_ptr 或 std::shared_ptr (C++11),或 boost::shared_ptr 和 boost::scope_ptr(如果不允许 C++11)。

【讨论】:

  • 按照您所说的操作我的代码后,我收到以下错误错误 C2665:'std::pair<_ty1>::pair':3 个重载都不能转换所有参数类型 d :\jzon\sample.cpp 16
【解决方案2】:

我认为你的意思是下面的typedef

typedef std::pair<std::string, std::string *> NamedNode;

int main()
{
    std::string name = "name";
    std::string *value = new std::string( "value" ) ;
    auto p = NamedNode( name, value );
    delete value;
}

如果你的意思是

typedef std::pair<std::string, std::string &> NamedNode;

然后 main 看起来像

int main()
{
    std::string name = "name";
    std::string *value = new std::string( "value" ) ;
    auto p = NamedNode( name, *value );
    delete value; // or delete p.second;
}

这里有另外两种方法

#include <iostream>
#include <utility>
#include <string>
#include <tuple>
#include <memory>

int main() 
{
    std::string name = "name";
    std::string *value = new std::string( "value" ) ;

    auto p = std::tie( name, *value );

    auto p1 = 
        std::make_pair( name, std::unique_ptr<std::string>( new std::string( "value" ) ) );

    delete value;

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多