Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/131.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在循环外部定义的变量的范围?_C++_C++11 - Fatal编程技术网

C++ 在循环外部定义的变量的范围?

C++ 在循环外部定义的变量的范围?,c++,c++11,C++,C++11,下面的代码用于将字符串中的连续重复字符替换为仅出现一次 e.g. "AAAABBBB" -> "AB" 当我退出for循环并在temp中打印值时,我的期望是得到字符串单词的最后一个字母。但是,我得到了字符串的第一个字母(即,使用我初始化的temp值) 但是如果我删除for循环中的重新初始化,上面的代码工作得非常好: string processString(string word) { char temp = word[0]; string result = ""; int

下面的代码用于将字符串中的连续重复字符替换为仅出现一次

e.g. "AAAABBBB" -> "AB" 
当我退出for循环并在temp中打印值时,我的期望是得到字符串单词的最后一个字母。但是,我得到了字符串的第一个字母(即,使用我初始化的temp值)

但是如果我删除for循环中的重新初始化,上面的代码工作得非常好:

string processString(string word) {
  char temp = word[0];
  string result = "";
  int size = word.size();
  for(int i=0; i<size; i++) {
    if(word[i] == temp) {
      continue;
    } else {
      result += temp;
      temp = word[i];
    }
  }
  cout << "TEMP : " << temp << endl;
  return result + temp;
}

你知道为什么会这样吗?为什么在FOR循环中重新初始化它会产生如此大的差异?

FOR(int i=0,temp=word[0];i一个名为
temp
的新变量在
FOR
循环中声明为
int

for(int i=0,temp=word[0];i<size;i++)
for(int i=0,temp=word[0];i<size;i++){

for(int i=0,temp=word[0];i在
for
循环中,您没有重新初始化
temp
。您正在创建一个名为
temp
的全新
int
变量,该变量将外部
temp
隐藏起来:

for(int i=0,temp=word[0];i<size;i++){
            ^^^^ brand new `temp'

关于阴影,其他答案是正确的,但仅供参考,您的函数可以简单地写成:

#include <string>
#include <iterator>
#include <algorithm>

std::string unique(std::string const &source)
{
    std::string result;

    std::unique_copy(src.begin(), src.end(),
                     std::back_inserter(result));
    return result;
}
#包括
#包括
#包括
std::string unique(std::string常量和源)
{
std::字符串结果;
std::unique_copy(src.begin(),src.end(),
标准:背向插入器(结果);
返回结果;
}

for
循环的
将使用内部循环,而不会更改外部循环。另一个很好的例子说明了为什么在高警告级别编译是一个好主意!其他编译器也会在'result+=temp'行发出关于int到char转换的警告。我认为这是理想的结果(只是折叠相同字符的运行),问题实际上是关于
temp
…的打印值。也许OP可以澄清?(输出匹配OP的好输出和坏输出AFAIC-只有temp行不同)。
for(int i=0,temp=word[0];i<size;i++){
for(int i=0,temp=word[0];i<size;i++){
            ^^^^ brand new `temp'
$ g++ -Wshadow test.cpp
test.cpp: In function 'std::string processString(std::string)':
test.cpp:10:15: warning: declaration of 'temp' shadows a previous local [-Wshadow]
test.cpp:7:8: warning: shadowed declaration is here [-Wshadow]
#include <string>
#include <iterator>
#include <algorithm>

std::string unique(std::string const &source)
{
    std::string result;

    std::unique_copy(src.begin(), src.end(),
                     std::back_inserter(result));
    return result;
}