我坐在C ++ Primer(3.23)上的一个小练习上将近2天。我尝试了多种方法来为分配值vector<int>
。到目前为止,我将为您提供一个实际的练习和代码,但这完全是错误的。我做了很多研究,但没有发现任何用处。
编写一个程序来创建一个vector
包含10个int
元素的。使用迭代器,为每个元素分配一个为其当前值两倍的值。通过打印测试程序vector
这是我的代码
int main(){
vector<int> num(10);
for (auto it=num.begin();it != num.end() ;++it)//iterating through each element in vector
{
*it=2;//assign value to vector using iterator
for (auto n=num.begin() ;n!=num.end();++n)//Iterating through existing elements in vector
{
*it+=*n;// Compound of elements from the first loop and 2 loop iteration
}
cout<<*it<<" ";
}
keep_window_open("~");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的问题是我不知道如何使用迭代器int
为每个vector
元素分配值(我为1分配了五个元素,但没有给五个元素分配值)!此外,我在如何使用中的10个元素来完成此练习时大吃一惊vector
,因为每个元素必须具有不同的值,并且迭代器必须执行赋值。
感谢您的时间。
我目前正在使用字数统计程序。我有一个棘手的练习。
我不明白这个练习到底要我做什么。
这里的练习本身
修改字数统计程序以使用更好的“单词”定义,例如以字母开头的字母、数字和撇号的序列
我无法得到它真正想要的东西。它希望我计算符号、数字、撇号或以太,它希望我为所有这些符号、数字等命名,比如“单词”,-将是A(") word comma(,) A(")
或有其他东西。
这是计算行数、字符数和换行数的程序
#include <stdio.h>
#define YES 1
#define NO 0
main ()
{
// CTRL+Z will Signal to EOF-End of File
int c,nl,nw,nc,inword; //nl -new line
//nw -new word
//nc -new chatacter
//inword -program in word or not
inword=NO;
nl=nw=nc=0;
while ((c=getchar()) !=EOF)
{
++nc;
if (c == '\n')
++nl;
if (c == ' ' || c == '\t' || c == '\n')
inword=NO;
else if (inword==NO)
{
inword=YES;
++nw;
} …
Run Code Online (Sandbox Code Playgroud)