【问题标题】:returning a std::string with an vector返回带有向量的 std::string
【发布时间】:2010-07-30 22:06:28
【问题描述】:

我正在尝试让“CMtoaPlugin::listArnoldNodes()”返回一个字符串“数组”

   std::vector<std::string> ArnoldNodes = CMtoaPlugin::listArnoldNodes();
   std::vector<std::string>::iterator it;

   for ( it=ArnoldNodes.begin() ; it < ArnoldNodes.end(); it++ )
   {
      printf("initialize shader %s\n", *it);
   }

但这是我得到的,2 个条目,这是正确的,但条目的内容不是

初始化 Arnold 着色器†¡/

初始化 Arnold 着色器。

我做错了什么

【问题讨论】:

  • 您必须向我们展示 listArnoldNodes() 中的代码。

标签: c++ iteration stdstring stdvector


【解决方案1】:

您不能使用 printf(或任何可变参数方法)打印 std::string。 g++ 在这里给出警告:

warning: cannot pass objects of non-POD type ‘struct std::string’ through ‘...’; call will abort at runtime

只需使用 cout:

std::cout << "initialize shader " << *it << std::endl;

【讨论】:

    【解决方案2】:

    另一种可能是用printf打印std::string对应的C字符串,像这样:

     printf("initialize shader %s\n", it->c_str());
    

    【讨论】:

      【解决方案3】:

      试试这样:

      for (it = ArnoldNodes.begin() ; it != ArnoldNodes.end(); ++it)
      {
          std::cout << "initialize shader " << *it << std::endl;
      }
      
      • printf不适用于std::string,你需要使用cout(或者传递给it-&gt;c_str()
      • 在迭代器 for 循环中,最好使用 it != vec.end()(因为您只需要检查是否相等,而不是比较),并使用 ++it 来递增(对于某些迭代器来说,后递增的效率可能会降低)。

      【讨论】:

        【解决方案4】:

        当你在你的迭代器范围内循环时,你应该使用:

        for ( it = ArnoldNodes.begin() ; it != ArnoldNodes.end(); it++ )
        { /*...*/ }
        

        不同之处在于比较是!= 而不是&lt;,因为container.end() 迭代器返回容器的最后一个。它不一定更“正确”,但更惯用。

        【讨论】:

        • 真;然而,原因并不是container.end() 是过去式的,而是因为用&lt; 编写的循环仅适用于RandomAccessIterators,而!= 适用于所有这些循环。
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-06-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多