方法std::basic_string::substr
有参数pos, count
,指定逻辑范围内的元素位置[pos, pos + count + 1)。相反,大多数标准库函数(例如std::for_each
)具有类似于begin, end
的某种形式的参数,指定范围[begin, end)。
std::vector::erase
遵循了通常的约定。方法std::basic_string::substr
有参数pos, count
,指定逻辑范围内的元素位置[pos, pos + count + 1)。相反,大多数标准库函数(例如std::for_each
)具有类似于begin, end
的某种形式的参数,指定范围[begin, end)。
std::vector::erase
遵循了通常的约定。历史原因。标准库有多个起源之一是STL。它引入了begin,end
的约定。std::string
早于STL合并到标准库,已经有大量现有代码使用.substr(pos,length)
。
std::string
看起来会非常不同。 - Martin Bonner supports Monica一个简单的猜测:
你提到的不同方法有不同的行为,这可能是为什么有些使用迭代器而有些不使用的原因。
std::for_each
是通用的 - 在任何容器(甚至是原始数组)上工作的通用方法最简单的方法就是使用迭代器。
std::vector::erase
是序列容器概念的一部分,因此它必须具有可以在任何类型的容器上工作的“通用”形式(您可以为std::vector
使用pos
和count
,但对于std::list
或std::set
呢?)。拥有这样的概念对于创建通用代码非常有用:
template <typename C>
void real_remove(C &c, const typename C::value_type &value) {
c.erase(std::remove(c.begin(), c.end(), value), c.end());
}
std::...::erase
都是定义明确的。另一方面,std::basic_string::substr
仅作为std::basic_string
的一部分存在(与erase
不同,erase
是std::vector
、std::list
等的一部分),并返回一个std::basic_string
1 (不是迭代器,在这里你会用迭代器做什么?)。std::basic_string
中有其他“非通用”(即没有一些概念的强制要求)方法,通常是整个find
系列方法、insert
带有size_type
的重载版本、append
等等。std::basic_string
,它的行为不能像其他容器那样,因为它不是(我不确定标准是否要求std::basic_string
是一个SequenceContainer
或类似物)。
1 在这里不能返回迭代器,因为你需要一个新的std::basic_string
,所以你将拥有一个接受迭代器但返回对象的方法...... 我觉得这比使用pos
/count
而不是first
/last
更令人不安。
template< class InputIt >
basic_string( InputIt first, InputIt last,
const Allocator& alloc = Allocator() );
std::string substring{text.begin(), text.end()}
。不知道为什么substr
没有这样的重载。 - Zeregesstd::string::substr()
重载,而不是也可以将它们传递给std::string::string()
。 - MSalters