我试图通过初始化程序列表初始化2D std :: array但是编译器告诉我初始化程序太多了.
例如:
std::array<std::array<int, 2>, 2> shape = { {1, 1},
{1, 1} };
Run Code Online (Sandbox Code Playgroud)
编译错误:错误:初始化程序太多 ‘std::array<std::array<int, 2ul>, 2ul>’
但显然没有太多.难道我做错了什么?
在python中,以下指令:print 'a'*5将输出aaaaa.std::ostream为了避免for构造,如何在C++中结合s 编写类似的内容?
我正面临着一个令人讨厌的问题,这个问题一直困扰着编程.我打算开始一个个人项目,我需要使用数据库来存储某些信息,然后我决定使用SQLite,但我不喜欢C-ish API,所以我在SQLite wiki中遇到了SOCI包装器.
我去了官方的SOCI网站,阅读文档并决定试一试.我按照文档"安装"一章中的说明进行操作,在安装完所有要求后,我编译并安装它:
cmake -DWITH_BOOST=ON -DSOCI_TESTS=ON -DWITH_SQLITE3=ON
make
make test
sudo make install
Run Code Online (Sandbox Code Playgroud)
所有测试都成功完成,但是在尝试运行(编译后g++ test.cpp -o1 -lsoci_core -lsoci_sqlite3)这样的程序时:
TEST.CPP:
#include "soci/soci.h"
#include "soci/sqlite3/soci-sqlite3.h"
#include <iostream>
int main()
{
soci::session sql(soci::sqlite3, "testdb.db");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息:"加载共享库时出错:libsoci_sqlite3.so.3.1:无法打开共享对象文件:没有这样的文件或目录." 但是看一下安装日志,我可以清楚地看到已经安装了共享库.
我发现自己编写了很多类型别名(typedef)来使代码更容易更改,但同时有些东西告诉我要避免这样做,因为它会给那些打算和我一起工作的人造成很多困惑.码.
也许不是最好的例子,但看看这里.我还会举一个最近的例子; 这些是我在构建XML解析器时乱搞的一些类:
namespace XML
{
struct Attribute
{
typedef std::string name_t;
typedef std::string value_t;
Attribute(const name_t &name, const value_t &value = "");
name_t name;
value_t value;
};
}
namespace XML
{
class Element
{
private:
typedef std::list<Attribute> attribute_container;
typedef std::list<Element> element_container;
public:
typedef attribute_container::iterator attribute_iterator;
typedef attribute_container::const_iterator const_attribute_iterator;
typedef element_container::iterator element_iterator;
typedef element_container::const_iterator const_element_iterator;
typedef std::string name_t;
typedef std::string data_t;
...
private:
name_t _name;
data_t _data;
attribute_container _attributes;
element_container _child_elements;
Run Code Online (Sandbox Code Playgroud)
以这种方式做事使得编写代码变得更容易,也许这使得它有点直观,但这种做法的缺点是什么?
如何使用基于范围的元素和属性循环来完成这样的工作?
#include <list>
#include "XMLAttribute.h"
namespace XML
{
class Element
{
private:
typedef std::list<Attribute> attribute_container;
typedef std::list<Element> element_container;
public:
XMLElement();
bool has_attributes() const;
bool has_elements() const;
bool has_data() const;
const std::string &name() const;
const std::string &data() const;
private:
std::string _name;
std::string _data;
attribute_container _attributes;
element_container _elements;
};
}
Run Code Online (Sandbox Code Playgroud)
我希望能够使用类似的东西:
for (XML::Element &el : element) { .. }
for (XML::Attribute &at : element) { .. }
Run Code Online (Sandbox Code Playgroud)
并阻止类似的东西for (auto &some_name : element) { .. } //XML::Element or XML::Attribute?.
像这样实现它是一个好主意还是我应该改变我的设计?