Вы, вероятно, имели в виду
#include <cstdlib>
#include <iostream>
using namespace std;
int dupe(int arr1[], int nElements)
{
int value;
for(int i = 0; i < nElements; i++)
{
value = arr1[i];
for(int j = i + 1; j < nElements; j++)
{
if(value == arr[j])
return value;
}
}
}
int main()
{
int arr1[] = { 5, 1, 6, 3, 1 }, nElements;
nElements = sizeof(arr1) / sizeof(int);
cout << dupe(arr1, nElements);
}
Функция dupe действительно находит первый дубликат, который в данном случае является целевым значением, но не всегда.
Возможно, лучшим подходом будет сортировка массива (используя std :: sort в заголовке алгоритма). Это сделало бы все дубликаты смежными и, следовательно, было бы легко сосчитать.
Your code fails in Python 2.6, but works in 3.0.
This does work in 2.6, presumably because it allows the parser itself to figure out the encoding (perhaps by reading the encoding optionally specified on the first line of the XML file, and otherwise defaulting to utf-8):
def test(filename):
parser = xml.sax.make_parser()
parser.parse(open(filename))
The SAX parser in Python 2.6 should be able to parse utf-8 without mangling it. Although you've left out the ContentHandler you're using with the parser, if that content handler attempts to print any non-ascii characters to your console, that will cause a crash.
For example, say I have this XML doc:
<?xml version="1.0" encoding="utf-8"?>
<test>
<name>Champs-Élysées</name>
</test>
And this parsing apparatus:
import xml.sax
class MyHandler(xml.sax.handler.ContentHandler):
def startElement(self, name, attrs):
print "StartElement: %s" % name
def endElement(self, name):
print "EndElement: %s" % name
def characters(self, ch):
#print "Characters: '%s'" % ch
pass
parser = xml.sax.make_parser()
parser.setContentHandler(MyHandler())
for line in open('text.xml', 'r'):
parser.feed(line)
This will parse just fine, and the content will indeed preserve the accented characters in the XML. The only issue is that line in def characters()
that I've commented out. Running in the console in Python 2.6, this will produce the exception you're seeing because the print function must convert the characters to ascii for output.
You have 3 possible solutions:
One: Make sure your terminal supports unicode, then create a sitecustomize.py
entry in your site-packages
and set the default character set to utf-8:
import sys sys.setdefaultencoding ('utf-8')
Два : не выводить вывод на терминал (насмешливо)
Три : нормализовать вывод с использованием unicodedata .normalize
для преобразования символов, отличных от ascii, в эквиваленты ascii, или кодирование
символов в ascii для вывода текста: ch.encode ('ascii', 'replace')
. Конечно, используя этот метод, вы не сможете правильно оценить текст.
Используя вариант 1 выше, ваш код отлично работал для my в Python 2.5.
Джаррет Харди уже объяснил проблему. Но для тех из вас, кто кодирует для командной строки и, похоже, не видно "sys.setdefaultencoding", можно быстро обойти эту ошибку (или "функцию"):
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
Надеюсь, reload ( sys)
больше ничего не сломает.
Более подробная информация в этом старом блоге: