动态数组初始化

时间:2010-03-07 11:37:15

标签: c++ syntax

这有点奇怪,但这里有。

我有许多硬编码的“表格”,我将其定义为std::stringsconst char *的数组。

例如:

const char* resp_desc[] = {
    "00=Approved",
    "01=Declined",
    "03=Incorrect User name",
    // more values
    NULL
};

在某些函数中,这些函数作为表传递以查找描述:

const char* lookup(const char* code, const char** table, const char*default="") {
    // lookup code is here..
}

我的问题是,是否可以在没有创建resp_desc数组的情况下调用查找函数

以下代码是我的第一次尝试,但在尝试使用时,我在{}周围出现语法错误:

const char* desc = lookup("00", {"00=Approved", "01-Invalid Record", NULL})

5 个答案:

答案 0 :(得分:3)

它不适用于当前的C ++ 03,但C ++ 0x将允许初始化,即std :: vector with

std::vector<std::string>{"00=Approved", "01-Invalid Record"}

编辑:这适用于g ++ --std = c ++ 0x(gcc --version是4.4.3)

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

using namespace std;

bool contains(string item, vector<string> const& table) {
  return find(table.begin(), table.end(), item) != table.end();
}

int main() {
  cout << (contains("foo", vector<string>{"foo", "bar"}) ? "found" : "not found") << "\n";
  return 0;
}

答案 1 :(得分:2)

如果您愿意更改查找功能,可以选择使用Boost.Assign这样的实用程序:

// alternative lookup function:
std::string lookup(const std::string& code, 
                   const std::vector<std::string>& table, 
                   const std::string& default="");

// example:
const std::string desc = lookup("00", boost::assign::list_of
                                ("00=Approved")("01-Invalid Record"));

或者可能只是这样的事情:

typedef std::map<std::string,std::string> Table;
std::string lookup(const std::string& code, 
                   const Table& table, 
                   const std::string& default="")
{
    Table::iterator it = table.find(code);
    return (it != table.end()) ? it->second : default;
}

const std::string desc = lookup("00", boost::assign::map_list_of
                                ("00","Approved")("01","Invalid Record"));

答案 2 :(得分:1)

简而言之,没有。 C ++不提供数组或结构文字,只提供数组或结构初始值设定项。也就是说,{ yadda, yadda, yadda }语法表示sometype name[] =右侧出现的内容。

答案 3 :(得分:1)

答案是否定的。

在C ++(以及C)中,函数参数中的数组类型会自动转换为指针类型,因为查找的签名显示:

const char* lookup(const char* code, const char** table, const char *default);

tableconst char **,因此需要指针值。要有一个指针,你需要一个内存中的对象指向。

如果您有一个简单的功能,例如:

void myfunc(int foo);

你可以致电myfunc(1),那没关系。常量表达式1是一个临时值,在内存中没有位置,myfunc直接接收该值。

但是,如果您调用查找函数:

const char* desc = lookup("00", /* array constant */);

我们可以问:/* array constant */可能是什么? lookup需要一个指向存在于内存中的数组对象的指针;但是常量表达式在内存中没有位置(它不是左值或对象),因此没有指针引用常量数组表达式。结果,不存在这样的常量表达式。

(“没有常量衰减到指针”这一规则的一个例外是字符串文字:"Hello World"。字符串文字在内存中创建一个静态持续时间的数组,该数据存在于程序的生命周期中,返回的值是指向该数组的const char *。遗憾的是,数组文字的等价物不存在。)

答案 4 :(得分:0)

不,先生!大括号语法仅用于数组初始化。它不代表文字数组。