我有一个关于在c ++ 11中定义向量的新快捷方式的问题.假设我有以下课程
struct Tester{
vector< vector<int> > data;
Tester(){
data = vector< vector<int> >();
}
void add(vector<int> datum){
data.push_back(datum);
}
};
Run Code Online (Sandbox Code Playgroud)
然后,以下按预期工作:
int main(){
Tester test = Tester();
vector<int> datum = vector<int>{1,2,3};
test.add(datum);
}
Run Code Online (Sandbox Code Playgroud)
但这不是:
int main(){
Tester test = Tester();
test.add(vector<int>{1,2,3});
}
Run Code Online (Sandbox Code Playgroud)
有人可以向我解释一下这个区别吗?如何在第二个main()中执行我尝试的快捷方式?
我有以下代码:
#include <iostream>
#include <vector>
struct C {
int a;
C() : a(0) {}
C(int a) : a(a) {}
};
std::ostream &operator<<(std::ostream &os, const C &c) {
os << c.a;
return os;
}
using T = std::vector<C>;
int main() {
auto v = T({5});
for (const auto &a : v) {
std::cout << a << ", ";
}
std::cout << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
如果我使用 g++,它会打印:
#include <iostream>
#include <vector>
struct C {
int a;
C() : a(0) {}
C(int …Run Code Online (Sandbox Code Playgroud) c++ vector initializer-list compiler-specific direct-initialization
我有一个函数func被重载以接受一个std::vector<Obj>参数或一个Obj参数。
#include <vector>
#include <iostream>
class Obj {
int a = 6;
};
void func(const std::vector<Obj>& a) {
std::cout << "here" << std::endl;
}
void func(const Obj& a) {
std::cout << "there" << std::endl;
}
int main() {
Obj obj, obj2;
func({obj});
func({obj, obj2});
}
Run Code Online (Sandbox Code Playgroud)
实际输出:
there
here
Run Code Online (Sandbox Code Playgroud)
预期产量:
here
here
Run Code Online (Sandbox Code Playgroud)
似乎{obj}不是初始化向量,而是初始化一个对象。我猜要初始化的类型有一些优先顺序。如何精确控制?
(使用g ++(Ubuntu 8.3.0-6ubuntu1)8.3.0编译的示例。)
我发现了一个可能的重复项(函数调用中的c ++ 11单元素矢量初始化),尽管我的问题仍然没有得到回答:
我知道{obj}可以解析为对象,而不是单个元素的向量,并且前者优先。但是,有没有一种方法可以{}用来创建单个项目向量(从而foo解决std::vector重载问题)?我可以显式创建向量,但{}看起来更好。
通过函数时,我遇到了常量单元素std :: vector的问题.当std :: vector变量包含单个元素时,C++编译器会自动调用错误的函数.这是C++设计的政策.但是,在这种情况下是否有任何明确的方法来指定.以下是问题的例子
assume i have two overload functions both have the same name "foo"
void foo(const std::vector<int> A)
{
// do vector operator
printf("vector thing");
}
void foo(int a)
{
// do integer operator
printf("integer thing")
}
Run Code Online (Sandbox Code Playgroud)
通常情况下,这两个函数都被正确调用
foo({1,2,3}); // print do vector thing
foo( 3 ); // print do integer thing
Run Code Online (Sandbox Code Playgroud)
但是来自c ++规则.打电话的时候
foo({5}); // print do integer thing ( I want it to call as vector )
Run Code Online (Sandbox Code Playgroud)
其中一种方法是创建一个变量
std::vector<int> B = { 5 };
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题. …