我做了一个v[-5,-3]的向量。我iti为它的开头分配了一个迭代器,然后将另一个迭代器分配itj为iti+1. 由于我的向量只有 2 个元素,我认为这itj被认为是向量的结尾或v.end(). 但事实并非如此。
任何想法为什么会发生这种情况?
vector<int>v;
v.push_back(-5);
v.push_back(-3);
vector<int>::iterator iti, itj;
iti = v.begin();
itj = iti + 1;
if(itj==v.end())
cout << "1";
else
cout << "2";
Run Code Online (Sandbox Code Playgroud)
为什么这会打印出“2”而不是“1”?
我的任务是按长度递增的顺序对字符串中的单词进行排序,对于相同长度的单词,我必须按照给定的顺序对它们进行排序。例如:“成为或不成为”将变成“成为或不成为”。我首先制作字符串中所有单词的向量“v”,然后尝试使用 C++ 的 sort() 函数中的用户定义函数对向量进行排序。这是我的代码:
#include <bits/stdc++.h>
using namespace std;
static bool comparelength(string first,string second){//function to compare length
return first.size()<second.size();
}
int main() {
string text="Jlhvvd wfwnphmxoa qcuucx qsvqskq cqwfypww dyphntfz hkbwx xmwohi qvzegb ubogo sbdfmnyeim tuqppyipb llwzeug hrsaebveez aszqnvruhr xqpqd ipwbapd mlghuuwvec xpefyglstj dkvhhgecd kry";
vector<string> v;
string cur="";
text+=" ";
for(int i=0;i<text.size();i++){
if(text[i]==32){//if space is encountered then the word is inserted in the vector
v.push_back(cur);
cur="";
}
else{
cur+=text[i];//if not space then text[i] is added to the current …Run Code Online (Sandbox Code Playgroud)