【问题标题】:How to pass a vector to execvp如何将向量传递给 execvp
【发布时间】:2011-05-01 06:41:13
【问题描述】:

我想将一个向量作为第二个参数传递给 execvp。有可能吗?

【问题讨论】:

标签: c++ vector execvp


【解决方案1】:

是的,通过利用向量使用的内部数组,它可以非常干净地完成。

这会起作用,因为标准保证其元素是连续存储的(请参阅https://stackoverflow.com/a/2923290/383983

#include <vector>

using namespace std;

int main(void) {
  vector<char *> commandVector;

  // do a push_back for the command, then each of the arguments
  commandVector.push_back("echo");
  commandVector.push_back("testing");
  commandVector.push_back("1");
  commandVector.push_back("2");
  commandVector.push_back("3");  

  // push NULL to the end of the vector (execvp expects NULL as last element)
  commandVector.push_back(NULL);

  // pass the vector's internal array to execvp
  char **command = &commandVector[0];

  int status = execvp(command[0], command);
  return 0;
}

【讨论】:

  • 从C++11开始也可以使用std::vector::data()来获取内部数组。
  • 关于处理deprecated conversion from string constant to ‘std::vector&lt;char*&gt;::value_type {aka char*}’ [-Wwrite-strings] 将字符串常量推送到commandVector 的警告有什么建议吗?
  • 是的,这是 C++ 中必须使用 const_cast 或真正使代码复杂化的情况之一(将所有这些值复制到 char* 变量中,不值得)
【解决方案2】:

是的,它可以通过利用向量使用的内部数组来完成。

这会起作用,因为标准保证其元素是连续存储的(请参阅https://stackoverflow.com/a/2923290/383983

#include <vector>

using std::vector;

int main() {
  vector<char*> commandVector;

  // do a push_back for the command, then each of the arguments
  commandVector.push_back(const_cast<char*>("echo"));
  commandVector.push_back(const_cast<char*>("testing"));
  commandVector.push_back(const_cast<char*>("1"));
  commandVector.push_back(const_cast<char*>("2"));
  commandVector.push_back(const_cast<char*>("3"));

  // push NULL to the end of the vector (execvp expects NULL as last element)
  commandVector.push_back(NULL);

  int status = execvp(command[0], &command[0]);
  return 0;
}

执行 const_cast 以避免“从字符串常量到 'char*' 的不推荐转换”。字符串文字在 C++ 中实现为“const char*”。 const_cast 是这里最安全的强制转换形式,因为它只删除了 const 而没有做任何其他有趣的事情。 execvp 无论如何都不会编辑这些值。

如果您想避免所有类型转换,则必须通过将所有值复制到不值得的 'char*' 类型来使代码复杂化。

【讨论】:

    【解决方案3】:

    不是直接的;您需要以某种方式将向量表示为以 NULL 结尾的字符串指针数组。如果它是一个字符串向量,那很简单;如果是其他类型的数据,您必须弄清楚如何将其编码为字符串。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      • 2014-08-09
      • 1970-01-01
      • 2021-12-10
      • 2016-07-24
      • 2015-08-07
      • 1970-01-01
      相关资源
      最近更新 更多