c++空和数组索引
C++ empty and array index
是否可以这样做:
string word = "Hello";
word[3] = null;
if(word[3] == null){/.../}
c++中的,基本上使数组元素为空。例如,如果我想从数组中删除重复字符,我首先将它们设置为null,然后每次发现包含null的数组索引时,都将数组向左移动。
如果这是不可能的,那么在c++中有什么好的方法来做这样的事情呢?
如果您想要删除相邻的重复字符,您可以这样做:
std::string::iterator new_end = std::unique(word.begin(), word.end());
word.erase(new_end, word.end());
如果您想标记任意字符以删除,您可以跳过标记,只向std::remove_if
提供适当的谓词:
new_end = std::remove_if(word.begin(), word.end(), IsDuplicate);
word.erase(new_end, word.end());
然而,我想不出一个合适的谓词可以在这里使用,而不显示未定义的行为。我只需要写我自己的算法:
template<typename IteratorT>
IteratorT RemoveDuplicates(IteratorT first, IteratorT last)
{
typedef typename std::iterator_traits<IteratorT>::value_type
ValueT;
std::map<ValueT, int> counts;
for (auto scan=first; scan!=last; ++scan)
{
++counts[*scan];
if(counts[*scan] == 1)
{
*first = std::move(*scan);
++first;
}
}
return first;
}
或者,如果您不关心元素的顺序,您可以简单地对其排序,然后使用第一个解决方案
这是可能的,因为字符串的单个元素是字符数组中的元素,因此可以用指针表示,也就是说,您可以检索元素的地址。因此可以设置word[3] = null
。你的if
-构造是有效的,但编译器打印一个警告,这是因为NULL
只是一个指针常数。其他选项为:if (!word[3])
或if(word[3] == 0)
。
但是在任何情况下,您都应该考虑使用STL算法来删除重复项。
我认为你应该看看STL中的算法。
你不是很明确你想要删除什么,但也许这有帮助:
std::string string_with_dup("AABBCCDD");
std::string string_without_dup;
std::cout << string_with_dup << std::endl;
// with copy
std::unique_copy(string_with_dup.begin(), string_with_dup.end(), std::back_inserter(string_without_dup));
std::cout << string_without_dup << std::endl;
// or inplace
string_with_dup.erase(std::unique(string_with_dup.begin(), string_with_dup.end()), string_with_dup.end());
std::cout << string_with_dup << std::endl;
如果要删除所有重复项(不仅仅是相邻的重复项),应该使用擦除-删除习惯用法,如下所示
#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
struct is_repeated {
is_repeated( map<char,int>& x ) :r(&x) {};
map<char,int>* r;
bool operator()( char c ) {
(*r)[c]++;
if( (*r)[c] > 1 )
return true;
return false;
}
};
int main (int argc, char**argv)
{
map<char,int> counter_map;
string v = "hello hello hello hello hello hello hello";
cout << v << endl;
is_repeated counter(counter_map);
v.erase( remove_if(v.begin(), v.end(), counter ), v.end() );
cout << v << endl;
}
输出(截至此):
hello hello hello hello hello hello hello
helo
相关文章:
- 特征获取索引数组,其中向量中的值为真(不需要循环)
- 是否可以使用字符串或字符索引数组
- 为什么在使用字符索引数组时会出现这种不同的行为
- 在具有重复索引的索引数组处更改 ArrayFire 数组
- 使用索引数组订购 ArrayFire Array 的最佳方式
- C++ 中结构的动态索引数组
- 1索引数组上的qsort()正在扰乱索引
- C++ 索引数组打印和删除字符串名称 数组打印
- 字符串下标超出范围.我不知道如何使用字符索引数组,所以我使用了(无符号整数),但它不起作用
- openGL drawElements - 一个额外的三角形,使用索引数组
- 具有索引数组的地形(高度贴图)LOD
- 通过创建索引数组进行 C++ 排序
- OpenGL:两个顶点数组 + 两个索引数组
- 将索引数组排序为主数组
- 自动循环跳过某些索引数组
- 为静态强制转换的索引数组生成数组
- 重载枚举索引数组的std::get
- 使用c++中的第二个索引数组对数组进行排序
- 给定的零索引数组 &该数组的均衡索引
- CUDA:重新索引数组