首页 \ 问答 \ C ++ - 在STL向量中操作对象?(C++ - manipulating objects in a STL vector?)

C ++ - 在STL向量中操作对象?(C++ - manipulating objects in a STL vector?)

我有这样的结构:

struct Rz3DContourNode {
  float x;
  float y;
  float z;
  float nx;
  float ny;
  float nz;
};

我将元素存储在STL向量中,如下所示:

 std::vector < Rz3DContourNode >  nodes;

现在我想更改vector中节点的nx,ny compoent。我尝试如下:

*(&nodes[i].nx)=newNXValue;
*(&nodes[i].ny)=newNYValue;
*(&nodes[i].nz)=newNZValue;

这不起作用。是因为nodes [i]返回对象的副本?

使用指针有什么解决方案吗?

我不能使用指针(Rz3DContourNode *),因为我在OpenGL中使用此向量作为

glNormalPointer(GL_FLOAT,sizeof(Rz3DContourNode), &nodes[0].nx);

编辑 - 对不起。我实际上每次都保留一个QList并获取std :: vector。这就是原因

std::vector<Rz3DContourNode> nodeVector = nodes.toVector().toStdVector();

I have structure like this:

struct Rz3DContourNode {
  float x;
  float y;
  float z;
  float nx;
  float ny;
  float nz;
};

And I store elements in a STL vector as follows :

 std::vector < Rz3DContourNode >  nodes;

Now I want to change the nx,ny compoent of the nodes in the vector.I tried as follows:

*(&nodes[i].nx)=newNXValue;
*(&nodes[i].ny)=newNYValue;
*(&nodes[i].nz)=newNZValue;

This did not work.Is it because nodes[i] returns a copy of the object?

Is there any solution for this expect using pointers ?

I cannot use pointer (Rz3DContourNode*) , because I am using this vector in OpenGL as

glNormalPointer(GL_FLOAT,sizeof(Rz3DContourNode), &nodes[0].nx);

EDIT - I am sorry.I actually keep a QList and get the std::vector everytime.That was the reason

std::vector<Rz3DContourNode> nodeVector = nodes.toVector().toStdVector();

原文:https://stackoverflow.com/questions/7305629
更新时间:2022-09-09 16:09

最满意答案

您正在寻找的功能是Promise链接 ,它允许您构建一系列承诺,每个承诺取决于前一个值的结果。 将此应用于您的代码,您将获得以下内容:

exports.getArticleData = function(req, done) {
  pool.getConnection(function(error, connection) {
    if (error) throw error;

    // Inital query
    return connection.query(
        `SELECT article_id, title, is_listicle_article, FROM com_magazine_articles AS article WHERE article_id = ${req
            .params.articleId}`
    ).then((rows) => {
    
       return Promise.all(rows.map((article) => {
          if (article.is_listicle_article) {
            return connection.query(
                `SELECT * FROM com_magazine_article_listicles WHERE article_id = ${req.params
                    .articleId}`
             );
          } else {
             return Promise.resolve(null);
          }
       }));
    }).then((res) => {
     connection.release();
     done(res.filter(function(i){ return i != null; }));
    })

    // This query should only be excuted if is_listicle_article = true
    

    // More queries depending on the result of the first one
    // ....
    // ....

    // Callback with the data object
    connection.release();
  });
};

显然,因为我没有你的所有代码,我无法验证这个例子,但这应该大致是你正在寻找的功能。 也就是说,我认为在您的示例代码中应该注意一些错误:

  • connection.query()返回一个promise(也就是说不需要回调函数)。 使用此功能有利于您 - 它将使您的代码更漂亮。
  • connection.query()返回行数组,而不是单个值。 您似乎在示例代码中忽略了这一点。
  • 尝试在使用promises时不将内容保存到变量中,这是没有必要的。 要解决这个问题,请阅读Promise API(Promise.resolve(),Promise.reject(),Promise.any(),Promise.catch(),Promise.all())等。
  • 看起来这些SQL查询很容易组合成一个查询。 这将比执行两个操作更有效。 不确定您希望使用的其余查询是否属于这种情况,但绝对需要注意。

The functionality you are looking for is Promise chaining, it allows you to construct a sequence of promises, each depending on the result of the previous value. Applying this to your code, you would get something like this:

exports.getArticleData = function(req, done) {
  pool.getConnection(function(error, connection) {
    if (error) throw error;

    // Inital query
    return connection.query(
        `SELECT article_id, title, is_listicle_article, FROM com_magazine_articles AS article WHERE article_id = ${req
            .params.articleId}`
    ).then((rows) => {
    
       return Promise.all(rows.map((article) => {
          if (article.is_listicle_article) {
            return connection.query(
                `SELECT * FROM com_magazine_article_listicles WHERE article_id = ${req.params
                    .articleId}`
             );
          } else {
             return Promise.resolve(null);
          }
       }));
    }).then((res) => {
     connection.release();
     done(res.filter(function(i){ return i != null; }));
    })

    // This query should only be excuted if is_listicle_article = true
    

    // More queries depending on the result of the first one
    // ....
    // ....

    // Callback with the data object
    connection.release();
  });
};

Obviously since I don't have all of your code, I couldn't verify this example, but this should be roughly the functionality you are looking for. That said, I think there were a couple of mistakes you should watch out for in your example code:

  • connection.query() returns a promise (aka doesn't need a callback function). Use this functionality to your advantage- it will make your code prettier.
  • connection.query() returns an array of rows, not a single value. You seemed to ignore this in your example code.
  • Try not to save things into a variable when using promises, it isn't necessary. To remedy this, read more into the Promise API (Promise.resolve(), Promise.reject(), Promise.any(), Promise.catch(), Promise.all()) etc.
  • It seems like these SQL queries could easily be combined into a single query. This will be way more efficient that performing two operations. Not sure if this is the case with the remaining queries you wish to use, but definitely something to look out for.

相关问答

更多
  • 我看到一些问题: function read(id, done) { con.getConnection(function(id, connection){...} } 注意如何通过将相同的名称赋予getConnection回调的参数来覆盖传递给read的id 。 此外,您的Express路由实际上并不通过发送回应来结束请求,这将使您的浏览器超时连接。 在某些时候,它甚至会拒绝发送更多请求,因为有太多请求仍在等待中。 所以一定要结束请求: app.get('/read', isLoggedIn, ...
  • 您正在寻找的功能是Promise链接 ,它允许您构建一系列承诺,每个承诺取决于前一个值的结果。 将此应用于您的代码,您将获得以下内容: exports.getArticleData = function(req, done) { pool.getConnection(function(error, connection) { if (error) throw error; // Inital query return connection.query( ...
  • 我讨厌回答我自己的问题,但我找到了解决方案。 我想念红色的文档。 可以通过在createConnection()函数中设置选项{multipleStatements:true}来实现。 所以它就像: mysqlConnection = mysql.createConnection({ host: settings.mysqlServer, user: settings.mysqlUser, password: settings.mysqlPassword, multipleS ...
  • 如果你的MySQL库自动处理连接的创建和处理,这可能会透明地处理,一些库有一个连接池。 如果它是单个连接,您必须根据定义等待。 Sequelize支持这一点 ,并且可能是一种更好的访问MySQL的方法,而不是打击低级驱动程序。 If your MySQL library handles creating and disposing of connections automatically this might be handled for you transparently, some libraries ...
  • 你的“IF NOT EXISTS”部分抑制了“错误”。 所以你可以: 只要做一个“CREATE DATABASE ABC” - 这应该会引发错误。 所以你可以做, if (err) {...do something...} 您可以事先检查数据库是否存在类似这样的内容“SELECT SCHEMA_NAME FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME ='ABC'” Your "IF NOT EXISTS" part suppresses the "er ...
  • 好。 我感到羞怯。 答案是代码没有任何问题,但数据库存在问题。 在MySQL工作台中,在之前的调试工作中,我没有选择Query> Auto-Commit Transactions,这导致事务和语句在第一个应用到给定行之后仍未提交(感谢InnoDB获取行特定的锁)。 虽然答案与代码无关,但在初始化数据库对象后添加此代码可能会产生相同的效果: pool.getConnection(function(err, conn){ if(err instanceof Error){ throw err; } co ...
  • 由于您没有使用var关键字声明rCarnet_achat ,因此您隐式将其声明为全局变量。 所以,每次调用rCarnet_achat.addElement(ordreToAdd); ,您实际上是在同一个 Carnet_achat实例中添加元素。 这可以通过添加var rCarnet_achat;来修复var rCarnet_achat; 到Zone功能的顶部。 ps你的代码充满了其他问题,例如 你应该使用node-mysql的查询字符串转义来避免SQL注入攻击,例如aConnection.query("SE ...
  • 我建议用async模块解决这个问题: var async = require("async"); // connection instance var conn; // here goes task serving logic // if any async function should be finished before drain callback, push them into q var solvers = { query: function(q, task, row){ ...
  • 请记住,Node.JS主要是异步的 。 使用app.get(...)声明的请求处理程序不会立即执行,而是仅在稍后,当收到第一个(或任何)请求时执行。 在声明请求处理程序之后,即使在处理第一个请求之前,您也正在使用con.end(...)调用关闭 MySQL连接。 当您尝试处理请求时, con已经关闭,因为您之前已经使用con.end关闭它。 您可能尝试实现的是在服务器关闭时关闭MySQL连接。 为此,您可以监听服务器的close事件(尽管未经测试): app.on('close', function() { ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)