如果没有其他变量,我如何获得当前职位
How can I get the current position without another variable?
很多时候在创建语法列表(使用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 << ")";
相关文章:
- 在执行其他功能的同时播放动画(LED矩阵和Arduino/ESP8266)
- 正在查找文档以获得PS4平台的C++中的设备信息
- 如何从C++中的依赖类型中获得它所依赖的类型
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 欧拉项目#8答案是大以获得有效答案
- 有没有什么方法可以使用一个函数中定义的常量变量,也可以由c++中同一程序中的其他函数使用
- 如何使用C/C++在MacOSX中获得键盘布局
- 访问其他网站后如何获得完整(精确)的URL / QUrl地址?
- 如何获得模板函数以查看以后定义的其他全局方法
- 如果从其他线程访问(读/写)src缓冲区,是否有可能从memcpy获得访问冲突
- 如何获得返回自身的boost::函数(或其他通用函数包装器)
- windeployqt错过了一些库,而获得了其他不需要的库
- 在不使用其他库的情况下获得高于 63 的答案 2
- 如果没有其他变量,我如何获得当前职位
- 如何获得其他附加显示器的屏幕分辨率
- 什么是最快的方式来获得日期,时间和解析成字符串以及一些其他信息
- 如何从其他命令行接口程序获得输出
- 获得类类型重定义和一些其他错误
- 如何比较同一对象的两个向量并获得其他元素
- 我如何在cocos2d-x中获得相同场景中的其他图层?