gpt4 book ai didi

c++ - 使用非 1 参数 ctor 初始化嵌入在 std::pair 中的 std::string?

转载 作者:行者123 更新时间:2023-11-30 03:35:05 25 4
gpt4 key购买 nike

如果我想构造带有一个以上参数的构造函数的嵌入式 std::string,是否可以构造一个 std::pair?

例如,这是合法的:

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

int main()
{
std::pair<int, int> pair(2, 3);
return 0;
}

...这是合法的:

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

int main()
{
std::pair<int, std::string> pair(2, "hello");
return 0;
}

...但我想知道是否可能出现以下情况:

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

int main()
{
std::pair<int, std::string> pair{2, {"hello", 3}}; //Unclear if some variation/combination of parentheses and curly braces can make this legal.
return 0;
}

认为以上是使用“统一初始化列表”的正确语法,但这对我的目的不起作用,因为我使用的是 C++11 之前的编译器。有什么方法可以使用 C++11 之前的语法实现这一目标吗?

澄清一下,我正在尝试使用这个 std::string 构造函数:

basic_string( const CharT* s,
size_type count,
const Allocator& alloc = Allocator() );

作为我问这个问题的背景,这是出于学术好奇(如果错误请纠正我):我认为像这样进行单行构造更有效,因为 std::pair并且它的成员是一次性创建和初始化的。而如果我做了这样的事情(使用 C++11 语法)...

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

int main()
{
std::pair<int, int> pair(2, 3);
std::pair<int, std::string> pair2 = {2, {"hello", 3}};
return 0;
}

...然后我在技术上创建了一个 std::pair<int, std::string>其成员是默认构造的,然后调用 std::pairoperator= , 然后调用 operator=关于这对成员。

最佳答案

随便写:

std::pair<int, std::string> pair( 2, std::string( "hello", 3 ) ); 

至于这个声明:

std::pair<int, std::string> pair2 = {2, {"hello", 3}};

那么实际上它等同于这个声明:

std::pair<int, std::string> pair{2, { "hello", 3}};

由于复制构造函数省略。考虑到没有赋值运算符,因为它是一个声明。

考虑以下示例:

#include <iostream>
#include <string>

int main()
{
struct Pair
{
std::string s;
int i;
Pair(int i, const std::string &s) : i(i), s(s)
{
std::cout << "Pair( int, std::string )" << std::endl;
}

Pair( const Pair &p) : i(p.i), s(p.s)
{
std::cout << "Pair( const Pair & )" << std::endl;
}
};

Pair p1{ 2, { "hello", 3 } };
Pair p2 = { 2, { "hello", 3 } };
}

程序输出为:

Pair( int, std::string )
Pair( int, std::string )

关于c++ - 使用非 1 参数 ctor 初始化嵌入在 std::pair 中的 std::string?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41516629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com