如果没有其他变量,我如何获得当前职位

How can I get the current position without another variable?

本文关键字:何获得 其他 变量 如果没有      更新时间:2023-10-16

很多时候在创建语法列表(使用comas)时,我使用与以下代码类似的代码:

std::stringstream list;
int i = 0;
for (auto itemListIt = itemList.begin(); itemListIt != itemList.end(); itemListIt++)
{
    list << *itemListIt;
    if (i < itemList.size() - 1) list << ", ";
    i++;
}

有没有更简洁的方法可以做到这一点,也许不需要额外的变量"i"?

为什么不测试一下你真正感兴趣的东西;"这个元素之后还有其他元素吗?"。

std::stringstream list;
for (auto it = roomList.begin(); it != itemList.end(); it++)
{
    list << *it;
    if ( it+1 != itemList.end() ) list << ", ";
}

有两种简单的解决方案。第一种是使用while循环:

auto itemListIt = itemList.begin();
while ( itemListIt != itemList.end() ) {
    list << *itemListIt;
    ++ itemListIt;
    if ( itemListIt != itemList.end() ) {
        list << ", ";
    }
}

第二种解决方案是稍微改变逻辑:如果后面还有", ",请加上前缀,如果没有第一个要素:

for ( auto itemListIt = itemList.begin(); itemListIt != itemList.end(); ++ itemListIt ) {
    if ( itemListIt != itemList.begin() ) {
        list << ", ";
    }
    list << *itemListIt;
}

您可以使用--items.end()对所有内容进行循环,直到倒数第二个。

然后使用items.back()输出最后一个。

#include <algorithm>
#include <iterator>
#include <sstream>
#include <vector>
#include <iostream>
int main()
{
    std::ostringstream oss;
    std::vector<int> items;
    items.push_back(1);
    items.push_back(1);
    items.push_back(2);
    items.push_back(3);
    items.push_back(5);
    items.push_back(8);
    if(items.size() > 1)
    {
        std::copy(items.begin(), --items.end(),
                  std::ostream_iterator<int>(oss, ", "));
        oss << "and ";
    }
    // else do nothing
    oss << items.back();
    std::cout << oss.str();
}

输出:

1, 1, 2, 3, 5, and 8

以下内容适用于任何InputIterator输入:

std::stringstream list;
auto it(std::begin(input)); //Or however you get the input
auto end(std::end(input));
bool first(true);
for (; it != end; ++it)
{
    if (!first) list << ", ";
    else first = false;
    list << *it;
}

或者没有额外的变量:

std::stringstream list;
auto it(std::begin(input)); //Or however you get the input
auto end(std::end(input));
if (it != end)
{
    list << *it;
    ++it;
}
for (; it != end; ++it)
{
    list << ", " << *it;
}

如果你想像其他人建议的那样,用映射或其他不能进行随机访问的迭代器来实现这一点,请检查第一个元素:

std::stringstream query;
query << "select id from dueShipments where package in (";
for (auto it = packageList.begin(); it != packageList.end(); it++)
{
    if (it != packageList.begin()) query << ", ";
    query << it->second;
}
query << ")";